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/
|
.devres/
|
||||||
.idea/
|
.idea/
|
||||||
.failed_packets/
|
.failed_packets/
|
||||||
|
tools/.*/
|
||||||
@@ -1,202 +1,61 @@
|
|||||||
|
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
|
||||||
Apache License
|
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
||||||
Version 2.0, January 2004
|
|
||||||
http://www.apache.org/licenses/
|
|
||||||
|
|
||||||
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,
|
“The Library” refers to a covered work governed by this License, other than an Application or a Combined Work as defined below.
|
||||||
and distribution as defined by Sections 1 through 9 of this document.
|
|
||||||
|
|
||||||
"Licensor" shall mean the copyright owner or entity authorized by
|
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.
|
||||||
the copyright owner that is granting the License.
|
|
||||||
|
|
||||||
"Legal Entity" shall mean the union of the acting entity and all
|
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”.
|
||||||
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.
|
|
||||||
|
|
||||||
"You" (or "Your") shall mean an individual or Legal Entity
|
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.
|
||||||
exercising permissions granted by this License.
|
|
||||||
|
|
||||||
"Source" form shall mean the preferred form for making modifications,
|
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.
|
||||||
including but not limited to software source code, documentation
|
1. Exception to Section 3 of the GNU GPL.
|
||||||
source, and configuration files.
|
|
||||||
|
|
||||||
"Object" form shall mean any form resulting from mechanical
|
You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL.
|
||||||
transformation or translation of a Source form, including but
|
2. Conveying Modified Versions.
|
||||||
not limited to compiled object code, generated documentation,
|
|
||||||
and conversions to other media types.
|
|
||||||
|
|
||||||
"Work" shall mean the work of authorship, whether in Source or
|
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:
|
||||||
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).
|
|
||||||
|
|
||||||
"Derivative Works" shall mean any work, whether in Source or Object
|
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
|
||||||
form, that is based on (or derived from) the Work and for which the
|
b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy.
|
||||||
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.
|
|
||||||
|
|
||||||
"Contribution" shall mean any work of authorship, including
|
3. Object Code Incorporating Material from Library Header Files.
|
||||||
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."
|
|
||||||
|
|
||||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
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:
|
||||||
on behalf of whom a Contribution has been received by Licensor and
|
|
||||||
subsequently incorporated within the Work.
|
|
||||||
|
|
||||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
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.
|
||||||
this License, each Contributor hereby grants to You a perpetual,
|
b) Accompany the object code with a copy of the GNU GPL and this license document.
|
||||||
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.
|
|
||||||
|
|
||||||
3. Grant of Patent License. Subject to the terms and conditions of
|
4. Combined Works.
|
||||||
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. Redistribution. You may reproduce and distribute copies of the
|
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:
|
||||||
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:
|
|
||||||
|
|
||||||
(a) You must give any other recipients of the Work or
|
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.
|
||||||
Derivative Works a copy of this License; and
|
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
|
5. Combined Libraries.
|
||||||
stating that You changed the files; and
|
|
||||||
|
|
||||||
(c) You must retain, in the Source form of any Derivative Works
|
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:
|
||||||
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
|
|
||||||
|
|
||||||
(d) If the Work includes a "NOTICE" text file as part of its
|
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.
|
||||||
distribution, then any Derivative Works that You distribute must
|
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.
|
||||||
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.
|
|
||||||
|
|
||||||
You may add Your own copyright statement to Your modifications and
|
6. Revised Versions of the GNU Lesser General Public License.
|
||||||
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.
|
|
||||||
|
|
||||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
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.
|
||||||
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.
|
|
||||||
|
|
||||||
6. Trademarks. This License does not grant permission to use the trade
|
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.
|
||||||
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.
|
|
||||||
|
|
||||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
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.
|
||||||
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.
|
|
||||||
+17
-3
@@ -7,14 +7,28 @@ import (
|
|||||||
"github.com/admin-else/strom/proto_base"
|
"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) {
|
func Connect(addr string) (ret *proto.Conn, err error) {
|
||||||
ret = &proto.Conn{}
|
s, err := Status(addr)
|
||||||
err = ret.SetVersion("1.21.8")
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
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.SetState(proto_base.Handshaking)
|
||||||
ret.CompressionThreshold = -1
|
ret.SetCompressionThreshold(-1)
|
||||||
ret.Actor = proto_base.Client
|
ret.Actor = proto_base.Client
|
||||||
ret.Conn, err = net.Dial("tcp", addr)
|
ret.Conn, err = net.Dial("tcp", addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
package modules
|
package client
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
|
||||||
"github.com/admin-else/strom/event"
|
"github.com/admin-else/strom/event"
|
||||||
"github.com/admin-else/strom/proto"
|
"github.com/admin-else/strom/proto"
|
||||||
@@ -14,8 +15,12 @@ type ConfigIgnorer struct {
|
|||||||
*proto.Conn
|
*proto.Conn
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *ConfigIgnorer) Default(event any) (err error) {
|
func (c *ConfigIgnorer) OnStart() (err error) {
|
||||||
fmt.Printf("%#v\n", event)
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *ConfigIgnorer) Default(event event.Anything) (err error) {
|
||||||
|
slog.Debug("Config ignorer", "packet", fmt.Sprintf("%#v", event))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,7 +28,7 @@ func (c *ConfigIgnorer) OnKnownPacks(packet *v1_21_8.ConfigurationToClientPacket
|
|||||||
return c.Send(&v1_21_8.ConfigurationToServerPacketCommonSelectKnownPacks{Packs: packet.Packs})
|
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{})
|
err = c.Send(&v1_21_8.ConfigurationToServerPacketFinishConfiguration{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
@@ -44,7 +49,14 @@ func (c *ConfigIgnorer) OnKeepAlive(packet *v1_21_8.ConfigurationToClientPacketK
|
|||||||
}
|
}
|
||||||
|
|
||||||
func IgnoreConfig(c *proto.Conn) (err error) {
|
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 {
|
if err != nil {
|
||||||
err = errors.Join(err, errors.New("failed to ignore config"))
|
err = errors.Join(err, errors.New("failed to ignore config"))
|
||||||
}
|
}
|
||||||
+113
-9
@@ -1,22 +1,126 @@
|
|||||||
package client
|
package client
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
"net"
|
"net"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
func LookupMinecraftSRV(host string, port uint16) (hostRet string, portRet uint16) {
|
type DNSCheckFunc func(addr string) error
|
||||||
hostRet = host // in case of error
|
|
||||||
portRet = port
|
// DoDns resolves a DNS name to an IP address
|
||||||
if port != 25565 {
|
// 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
|
return
|
||||||
}
|
}
|
||||||
_, srvs, err := net.LookupSRV("minecraft", "tcp", host)
|
if f == nil {
|
||||||
if err != nil || len(srvs) == 0 {
|
f = func(addr string) error { return nil }
|
||||||
|
}
|
||||||
|
|
||||||
|
err = f(host)
|
||||||
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
target := strings.TrimSuffix(srvs[0].Target, ".")
|
portN = uint16(porti)
|
||||||
hostRet = target
|
outIP, err := net.ResolveIPAddr("ip", host)
|
||||||
portRet = srvs[0].Port
|
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
|
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 (
|
import (
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
@@ -7,11 +7,8 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"github.com/admin-else/strom/api"
|
"github.com/admin-else/strom/api"
|
||||||
"github.com/admin-else/strom/client"
|
|
||||||
"github.com/admin-else/strom/crypto"
|
"github.com/admin-else/strom/crypto"
|
||||||
"github.com/admin-else/strom/event"
|
"github.com/admin-else/strom/event"
|
||||||
"github.com/admin-else/strom/proto"
|
"github.com/admin-else/strom/proto"
|
||||||
@@ -30,6 +27,12 @@ type LoginClient struct {
|
|||||||
GivenAccount *v1_21_8.LoginToClientPacketSuccess
|
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 {
|
type KickedDuringLoginErr struct {
|
||||||
text.Component
|
text.Component
|
||||||
}
|
}
|
||||||
@@ -38,7 +41,7 @@ func (k KickedDuringLoginErr) Error() string {
|
|||||||
return k.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)
|
err = fmt.Errorf("unexpected event: %#v", event)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -47,37 +50,12 @@ func (s *LoginClient) OnCycle(_ event.Tick) (err error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *LoginClient) OnStart(_ event.OnStart) (err error) {
|
func (s *LoginClient) OnClose(_ event.Close) (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})
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *LoginClient) OnCompress(compress *v1_21_8.LoginToClientPacketCompress) (err error) {
|
func (s *LoginClient) OnCompress(compress *v1_21_8.LoginToClientPacketCompress) (err error) {
|
||||||
s.CompressionThreshold = compress.Threshold
|
s.SetCompressionThreshold(compress.Threshold)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -87,7 +65,7 @@ func (s *LoginClient) OnEncrypt(packet *v1_21_8.LoginToClientPacketEncryptionBeg
|
|||||||
|
|
||||||
if packet.ShouldAuthenticate {
|
if packet.ShouldAuthenticate {
|
||||||
if s.Account.Ygg == "" {
|
if s.Account.Ygg == "" {
|
||||||
err = fmt.Errorf("the account has no token so we cant join online servers")
|
err = NoTokenErr
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
serverId := crypto.AuthDigest([]byte(packet.ServerId), sharedSecret, packet.PublicKey)
|
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)
|
pub, ok := pubAny.(*rsa.PublicKey)
|
||||||
if !ok {
|
if !ok {
|
||||||
err = fmt.Errorf("public key is not rsa")
|
err = BadPublicKeyTypeErr
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
verifyTokenEnc, err := rsa.EncryptPKCS1v15(rand.Reader, pub, packet.VerifyToken)
|
verifyTokenEnc, err := rsa.EncryptPKCS1v15(rand.Reader, pub, packet.VerifyToken)
|
||||||
@@ -145,28 +123,50 @@ func (s *LoginClient) OnSuccess(success *v1_21_8.LoginToClientPacketSuccess) (er
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *LoginClient) OnStart() (err error) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
func Login(c *proto.Conn, account *api.Account) (err error) {
|
func Login(c *proto.Conn, account *api.Account) (err error) {
|
||||||
err = c.Start(&LoginClient{
|
lc := &LoginClient{
|
||||||
Conn: c,
|
Conn: c,
|
||||||
Account: account,
|
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 {
|
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
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func ConnectAndLogin(connectTo string, account *api.Account) (c *proto.Conn, err error) {
|
func ConnectAndLogin(connectTo string, account *api.Account) (c *proto.Conn, err error) {
|
||||||
c, err = client.Connect(connectTo)
|
c, err = Connect(connectTo)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
err = c.Start(&LoginClient{
|
err = Login(c, account)
|
||||||
Conn: c,
|
|
||||||
Account: account,
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
err = errors.Join(errors.New("failed to login"), err)
|
err = errors.Join(FailedToLoginErr, err)
|
||||||
}
|
}
|
||||||
return
|
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
|
package data
|
||||||
|
|
||||||
// {
|
import (
|
||||||
|
"errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
// {
|
||||||
// "id": 0,
|
// "id": 0,
|
||||||
// "name": "air",
|
// "name": "air",
|
||||||
// "displayName": "Air",
|
// "displayName": "Air",
|
||||||
@@ -35,29 +39,43 @@ type Block struct {
|
|||||||
DefaultState int32
|
DefaultState int32
|
||||||
MinStateId int32
|
MinStateId int32
|
||||||
MaxStateId int32
|
MaxStateId int32
|
||||||
States []struct {
|
States []BlockState
|
||||||
Name string
|
Drops []int
|
||||||
Type string
|
BoundingBox string
|
||||||
NumValues int
|
|
||||||
}
|
|
||||||
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
|
var ok bool
|
||||||
if ret, ok = BlocksCache[v]; ok {
|
if ret, ok = BlocksCache[v]; ok {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var b []Block
|
var b []*Block
|
||||||
must(LoadVersionedJson(v, "blocks", &b))
|
must(LoadVersionedJson(v, "blocks", &b))
|
||||||
BlocksCache[v] = b
|
BlocksCache[v] = b
|
||||||
return 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) {
|
for _, b := range BlocksForVersion(version) {
|
||||||
if b.MinStateId <= stateId && stateId <= b.MaxStateId {
|
if b.MinStateId <= stateId && stateId <= b.MaxStateId {
|
||||||
block = b
|
block = b
|
||||||
@@ -66,3 +84,105 @@ func LookupBlockByStateId(version string, stateId int32) (block Block, ok bool)
|
|||||||
}
|
}
|
||||||
return
|
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)
|
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"
|
// "releaseType": "snapshot"
|
||||||
// },
|
// },
|
||||||
|
|
||||||
type ProtocolVersion struct {
|
type VersionInfo struct {
|
||||||
MinecraftVersion string
|
MinecraftVersion string
|
||||||
Version int
|
Version int32
|
||||||
DataVersion int
|
DataVersion int
|
||||||
UsesNetty bool
|
UsesNetty bool
|
||||||
MajorVersion string
|
MajorVersion string
|
||||||
ReleaseType 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 {
|
for _, v := range ProtocolVersions {
|
||||||
if v.MinecraftVersion == name {
|
if v.MinecraftVersion == name {
|
||||||
ret = v
|
ret = v
|
||||||
@@ -31,7 +31,7 @@ func LookUpProtocolVersionByName(name string) (ret ProtocolVersion, err error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func LookUpProtocolVersionByVersion(version int) (ret ProtocolVersion, err error) {
|
func LookUpVersionByProtocolVersion(version int32) (ret VersionInfo, err error) {
|
||||||
for _, v := range ProtocolVersions {
|
for _, v := range ProtocolVersions {
|
||||||
if v.Version == version {
|
if v.Version == version {
|
||||||
ret = v
|
ret = v
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func TestLookUpProtocolVersion(t *testing.T) {
|
func TestLookUpProtocolVersion(t *testing.T) {
|
||||||
version, err := data.LookUpProtocolVersionByVersion(772)
|
version, err := data.LookUpVersionByProtocolVersion(772)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Expected to find version 772, got error: %v", err)
|
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
|
package event
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
"reflect"
|
"reflect"
|
||||||
"strings"
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
LoopsPerSecond = 100 // i dunno seems reasonable
|
||||||
|
TimePerLoop = time.Second / LoopsPerSecond
|
||||||
)
|
)
|
||||||
|
|
||||||
type Loop struct {
|
type Loop struct {
|
||||||
HandlerFunctions map[reflect.Type][]reflect.Value
|
HandlerFunctions map[reflect.Type][]reflect.Value
|
||||||
Handlers []any
|
|
||||||
HandlerIndex int
|
Ctx context.Context
|
||||||
|
ErrChan chan error
|
||||||
|
cancel context.CancelFunc
|
||||||
}
|
}
|
||||||
|
|
||||||
type Unhandled struct {
|
type Unhandled struct {
|
||||||
@@ -23,8 +32,7 @@ type Anything struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type (
|
type (
|
||||||
OnStart struct{}
|
Tick struct{}
|
||||||
Tick struct{}
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// HandlerDoneErr will stop the event loop and return the error if provided.
|
// HandlerDoneErr will stop the event loop and return the error if provided.
|
||||||
@@ -32,6 +40,11 @@ type HandlerDoneErr struct {
|
|||||||
Return error
|
Return error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Close is fired when the loop shuts down.
|
||||||
|
type Close struct {
|
||||||
|
Reason error
|
||||||
|
}
|
||||||
|
|
||||||
func (e HandlerDoneErr) Error() string {
|
func (e HandlerDoneErr) Error() string {
|
||||||
return "HandlerDoneErr"
|
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.
|
// ErrDontForward will stop the event from being forwarded to other handlers, including anything handlers.
|
||||||
var ErrDontForward = errors.New("dont forward")
|
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 ValidateHandler(h any) (eventType reflect.Type, hv reflect.Value) {
|
||||||
func (l *Loop) FindHandlers() {
|
hv = reflect.ValueOf(h)
|
||||||
l.HandlerFunctions = make(map[reflect.Type][]reflect.Value)
|
if hv.Kind() != reflect.Func {
|
||||||
for _, inst := range l.Handlers {
|
panic("expected method")
|
||||||
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(), ")")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
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.
|
// 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
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *Loop) Start() (err error) {
|
func (l *Loop) startLoop() (err error) {
|
||||||
_ = *l // exit early on nil connection
|
_ = *l // exit early on nil loop
|
||||||
l.FindHandlers()
|
for {
|
||||||
err = l.Fire(OnStart{})
|
tickStartTime := time.Now()
|
||||||
for err == nil {
|
|
||||||
err = l.Fire(Tick{})
|
err = l.Fire(Tick{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
time.Sleep(TimePerLoop - time.Since(tickStartTime))
|
||||||
}
|
}
|
||||||
if errors.Is(err, HandlerDoneErr{}) {
|
if errors.Is(err, HandlerDoneErr{}) {
|
||||||
err = errors.Unwrap(err)
|
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
|
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 {
|
type IntervalTask struct {
|
||||||
F func() error
|
F func() error
|
||||||
@@ -33,18 +36,15 @@ func (t *Timer) Tick() (err error) {
|
|||||||
}
|
}
|
||||||
t.Interval[i] = task
|
t.Interval[i] = task
|
||||||
}
|
}
|
||||||
var triggerLater []OnceTask
|
for i, task := range t.Once {
|
||||||
for _, task := range t.Once {
|
|
||||||
if task.Trigger.After(time.Now()) {
|
if task.Trigger.After(time.Now()) {
|
||||||
err = task.F()
|
err = task.F()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
} else {
|
t.Once = slices.Delete(t.Once, i, i)
|
||||||
triggerLater = append(triggerLater, task)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
t.Once = triggerLater
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
module github.com/admin-else/strom
|
module github.com/admin-else/strom
|
||||||
|
|
||||||
go 1.24
|
go 1.25
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/go-viper/mapstructure/v2 v2.4.0
|
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/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 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
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 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
|
|||||||
+28
-32
@@ -2,8 +2,6 @@ package level
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
"io"
|
||||||
"math"
|
"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
|
var pallet []int32 // remember we can't use make because this is user-controlled data
|
||||||
for range palletLen {
|
for range palletLen {
|
||||||
entry, err := proto_base.DecodeVarInt(r)
|
var entry int32
|
||||||
|
entry, err = proto_base.DecodeVarInt(r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -60,7 +59,7 @@ func UnpackSingleValuePalette(r io.Reader, numberOfEntries int) (data []int32, e
|
|||||||
}
|
}
|
||||||
data = make([]int32, numberOfEntries)
|
data = make([]int32, numberOfEntries)
|
||||||
for i := range data {
|
for i := range data {
|
||||||
data[i] = int32(entry)
|
data[i] = entry
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -76,74 +75,71 @@ func LongsToData(data []uint64, n, bpe int32) (ret []int32) {
|
|||||||
return
|
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
|
var bitsPerEntry uint8
|
||||||
err = binary.Read(r, binary.BigEndian, &bitsPerEntry)
|
err = binary.Read(r, binary.BigEndian, &bitsPerEntry)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var blocksSlice []int32
|
|
||||||
fmt.Println("blocks bpe", bitsPerEntry)
|
|
||||||
switch bitsPerEntry {
|
switch bitsPerEntry {
|
||||||
case 0:
|
case 0:
|
||||||
blocksSlice, err = UnpackSingleValuePalette(r, BlocksPerChunkSection)
|
blocks, err = UnpackSingleValuePalette(r, BlocksPerChunkSection)
|
||||||
case 1, 2, 3, 4:
|
case 1, 2, 3, 4, 5, 6, 7, 8:
|
||||||
blocksSlice, err = UnpackArrayPalette(r, bitsPerEntry, BlocksPerChunkSection)
|
blocks, err = UnpackArrayPalette(r, bitsPerEntry, BlocksPerChunkSection)
|
||||||
case 5, 6, 7, 8:
|
|
||||||
err = errors.New("unimplemented")
|
|
||||||
default:
|
default:
|
||||||
blocksSlice, err = UnpackLongData(r, bitsPerEntry, BlocksPerChunkSection)
|
blocks, err = UnpackLongData(r, bitsPerEntry, BlocksPerChunkSection)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
blocks = [BlocksPerChunkSection]int32(blocksSlice)
|
|
||||||
return
|
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
|
// net.minecraft.world.chunk.PaletteProvider#forBiomes
|
||||||
var bitsPerEntry uint8
|
var bitsPerEntry uint8
|
||||||
err = binary.Read(r, binary.BigEndian, &bitsPerEntry)
|
err = binary.Read(r, binary.BigEndian, &bitsPerEntry)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var biomesSlice []int32
|
|
||||||
fmt.Println("biome bpe", bitsPerEntry)
|
|
||||||
switch bitsPerEntry {
|
switch bitsPerEntry {
|
||||||
case 0:
|
case 0:
|
||||||
biomesSlice, err = UnpackSingleValuePalette(r, BiomesPerChunkSection)
|
biomes, err = UnpackSingleValuePalette(r, BiomesPerChunkSection)
|
||||||
case 1, 2, 3:
|
case 1, 2, 3:
|
||||||
biomesSlice, err = UnpackArrayPalette(r, bitsPerEntry, BiomesPerChunkSection)
|
biomes, err = UnpackArrayPalette(r, bitsPerEntry, BiomesPerChunkSection)
|
||||||
default:
|
default:
|
||||||
biomesSlice, err = UnpackLongData(r, bitsPerEntry, BiomesPerChunkSection)
|
biomes, err = UnpackLongData(r, bitsPerEntry, BiomesPerChunkSection)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
biomes = [BiomesPerChunkSection]int32(biomesSlice)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
type ChunkSection struct {
|
func UnpackSection(r io.Reader) (blocks, biomes []int32, err error) {
|
||||||
BlockData [BlocksPerChunkSection]int32
|
|
||||||
BiomeData [BiomesPerChunkSection]int32
|
|
||||||
}
|
|
||||||
|
|
||||||
func UnpackSection(r io.Reader) (s ChunkSection, err error) {
|
|
||||||
var blockCount int16
|
var blockCount int16
|
||||||
err = binary.Read(r, binary.BigEndian, &blockCount)
|
err = binary.Read(r, binary.BigEndian, &blockCount)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
s.BlockData, err = UnpackBlockData(r)
|
blocks, err = UnpackBlockData(r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
s.BiomeData, err = UnpackBiomeData(r)
|
biomes, err = UnpackBiomeData(r)
|
||||||
if err != nil {
|
return
|
||||||
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
|
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
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Tag) Read(r io.Reader) (err error) {
|
func (s *Tag) Decode(r io.Reader) (err error) {
|
||||||
id := int8(0)
|
id := int8(0)
|
||||||
err = binary.Read(r, Order, &id)
|
err = binary.Read(r, Order, &id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -81,7 +81,7 @@ func (s *Tag) Read(r io.Reader) (err error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Tag) Write(w io.Writer) (err error) {
|
func (s *Tag) Encode(w io.Writer) (err error) {
|
||||||
id, err := getId(s.Value)
|
id, err := getId(s.Value)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
|
|||||||
+142
-35
@@ -3,19 +3,32 @@ package proto
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
"reflect"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/admin-else/strom/data"
|
"github.com/admin-else/strom/data"
|
||||||
"github.com/admin-else/strom/event"
|
"github.com/admin-else/strom/event"
|
||||||
"github.com/admin-else/strom/proto_base"
|
"github.com/admin-else/strom/proto_base"
|
||||||
|
"github.com/admin-else/strom/proto_generated"
|
||||||
)
|
)
|
||||||
|
|
||||||
var BadPacketTypeError = errors.New("bad packet type")
|
var (
|
||||||
var BadPacketIdError = errors.New("bad packet id")
|
BadPacketTypeErr = errors.New("bad packet type")
|
||||||
var PacketNotFullyDecodedError = errors.New("packet not fully decoded")
|
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 {
|
type UnCodablePacket struct {
|
||||||
Err error
|
Err error
|
||||||
Data []byte
|
Data []byte
|
||||||
@@ -40,6 +53,30 @@ type Conn struct {
|
|||||||
Actor proto_base.Actor
|
Actor proto_base.Actor
|
||||||
Version string
|
Version string
|
||||||
ProtocolVersion int32
|
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) {
|
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) {
|
func (c *Conn) SetVersion(version string) (err error) {
|
||||||
c.Version = version
|
versionData, err := data.LookUpVersionByName(version)
|
||||||
versionData, err := data.LookUpProtocolVersionByName(c.Version)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
c.ProtocolVersion = int32(versionData.Version)
|
c.ProtocolVersion = versionData.Version
|
||||||
|
c.Version = version
|
||||||
return
|
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) {
|
func (c *Conn) Send(packet proto_base.EncodeDecodeAble) (err error) {
|
||||||
//fmt.Println("send:", packet)
|
|
||||||
switch packet := packet.(type) {
|
switch packet := packet.(type) {
|
||||||
case *UnCodablePacket:
|
case *UnCodablePacket:
|
||||||
err = c.SendRaw(packet.Data)
|
err = c.SendRaw(packet.Data)
|
||||||
default:
|
default:
|
||||||
i, ok := LookupPacketInfoByTypeLookupPacketInfoByTypeAndMore(packet, c.State())
|
return c.sendRegisteredPacket(packet)
|
||||||
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
|
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)
|
packet, ok := LookUpTypeByPacketInfoAndCopyType(c.Actor.ReceiveDirection(), c.State(), id, c.ProtocolVersion)
|
||||||
if !ok {
|
if !ok {
|
||||||
packet = &UnCodablePacket{Err: BadPacketIdError, Data: packetBytes, Direction: c.Actor.ReceiveDirection()}
|
packet = &UnCodablePacket{Err: BadPacketIdErr, Data: packetBytes, Direction: c.Actor.ReceiveDirection()}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
err = packet.Decode(b)
|
err = packet.Decode(b)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
packet = &UnCodablePacket{Err: err, Data: packetBytes, Direction: c.Actor.ReceiveDirection()}
|
packet = &UnCodablePacket{Err: err, Data: packetBytes, Direction: c.Actor.ReceiveDirection()}
|
||||||
err = nil
|
err = nil
|
||||||
|
return
|
||||||
}
|
}
|
||||||
if b.Len() != 0 {
|
if b.Len() != 0 {
|
||||||
err = nil
|
err = nil
|
||||||
packet = &UnCodablePacket{Err: PacketNotFullyDecodedError, Data: packetBytes, Direction: c.Actor.ReceiveDirection()}
|
packet = &UnCodablePacket{Err: PacketNotFullyDecodedErr, Data: packetBytes, Direction: c.Actor.ReceiveDirection()}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
//fmt.Println("recv:", packet)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Conn) OnTick(_ event.Tick) (err error) {
|
func (c *Conn) OnTick(_ event.Tick) (err error) {
|
||||||
packet, err := c.Receive()
|
var packet proto_base.EncodeDecodeAble
|
||||||
if err != nil {
|
if c.receiveRoutine {
|
||||||
return
|
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
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Conn) Start(handlers ...any) (err error) {
|
func (c *Conn) Start() (err error) {
|
||||||
c.Loop = &event.Loop{}
|
if c.Loop == nil {
|
||||||
c.Handlers = append(c.Handlers, c)
|
c.Loop = &event.Loop{}
|
||||||
c.Handlers = append(c.Handlers, handlers...)
|
}
|
||||||
err = c.Loop.Start()
|
return c.Loop.Start()
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|||||||
+16
-32
@@ -7,7 +7,7 @@ import (
|
|||||||
"github.com/admin-else/strom/proto_generated"
|
"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) {
|
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 {
|
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) {
|
func LookupPacketInfoByType(packet proto_base.EncodeDecodeAble) (p proto_base.PacketInfo, ok bool) {
|
||||||
switch packet := packet.(type) {
|
for _, p := range proto_generated.Packets {
|
||||||
case *UnCodablePacket:
|
if reflect.TypeOf(p.Type) == reflect.TypeOf(packet) {
|
||||||
p = proto_base.PacketInfo{
|
return p, true
|
||||||
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
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func LookupPacketInfoByTypeLookupPacketInfoByTypeAndMore(packet proto_base.EncodeDecodeAble, state proto_base.State) (p proto_base.PacketInfo, ok bool) {
|
func LookupPacketInfoByTypeAndState(packet proto_base.EncodeDecodeAble, state proto_base.State) (p proto_base.PacketInfo, ok bool) {
|
||||||
switch packet := packet.(type) {
|
for _, p := range proto_generated.Packets {
|
||||||
case *UnCodablePacket:
|
if state == p.State && reflect.TypeOf(p.Type) == reflect.TypeOf(packet) {
|
||||||
p = proto_base.PacketInfo{
|
return p, true
|
||||||
Type: &UnCodablePacket{},
|
|
||||||
Name: "undecodeable",
|
|
||||||
Direction: packet.Direction,
|
|
||||||
State: -1,
|
|
||||||
PacketId: -1,
|
|
||||||
ProtocolVersion: -1,
|
|
||||||
}
|
}
|
||||||
default:
|
}
|
||||||
for _, p := range proto_generated.Packets {
|
return
|
||||||
if state == p.State && reflect.TypeOf(p.Type) == reflect.TypeOf(packet) {
|
}
|
||||||
return p, true
|
|
||||||
}
|
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
|
return
|
||||||
|
|||||||
+22
-8
@@ -8,6 +8,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
|
"sync"
|
||||||
|
|
||||||
"github.com/admin-else/strom/crypto"
|
"github.com/admin-else/strom/crypto"
|
||||||
"github.com/admin-else/strom/proto_base"
|
"github.com/admin-else/strom/proto_base"
|
||||||
@@ -15,22 +16,36 @@ import (
|
|||||||
|
|
||||||
type RawConn struct {
|
type RawConn struct {
|
||||||
net.Conn
|
net.Conn
|
||||||
R io.Reader
|
R io.Reader
|
||||||
W io.Writer
|
W io.Writer
|
||||||
CompressionThreshold int32
|
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) {
|
func (c *RawConn) SendRaw(rawPacketBytes []byte) (err error) {
|
||||||
//fmt.Println("send:", rawPacketBytes)
|
//fmt.Println("send:", rawPacketBytes)
|
||||||
var packetBytes []byte
|
var packetBytes []byte
|
||||||
if c.CompressionThreshold > 0 {
|
threshold := c.GetCompressionThreshold()
|
||||||
|
if threshold > 0 {
|
||||||
packetBuffer := bytes.NewBuffer(nil)
|
packetBuffer := bytes.NewBuffer(nil)
|
||||||
if int32(len(rawPacketBytes)) >= c.CompressionThreshold {
|
if int32(len(rawPacketBytes)) >= threshold {
|
||||||
err = proto_base.EncodeVarInt(packetBuffer, int32(len(rawPacketBytes)))
|
err = proto_base.EncodeVarInt(packetBuffer, int32(len(rawPacketBytes)))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
zW := zlib.NewWriter(packetBuffer)
|
zW := zlib.NewWriter(packetBuffer) // ignore we don't care about the result if it errors
|
||||||
_, err = zW.Write(rawPacketBytes)
|
_, err = zW.Write(rawPacketBytes)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
@@ -80,7 +95,7 @@ func (c *RawConn) ReceiveRaw() (packetBytes []byte, err error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
rawPacketBuffer := bytes.NewBuffer(rawPacketBytes)
|
rawPacketBuffer := bytes.NewBuffer(rawPacketBytes)
|
||||||
if c.CompressionThreshold > 0 {
|
if c.GetCompressionThreshold() > 0 {
|
||||||
var packetLen int32
|
var packetLen int32
|
||||||
packetLen, err = proto_base.DecodeVarInt(rawPacketBuffer)
|
packetLen, err = proto_base.DecodeVarInt(rawPacketBuffer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -106,7 +121,6 @@ func (c *RawConn) ReceiveRaw() (packetBytes []byte, err error) {
|
|||||||
} else {
|
} else {
|
||||||
packetBytes = rawPacketBytes
|
packetBytes = rawPacketBytes
|
||||||
}
|
}
|
||||||
//fmt.Println("recv:", packetBytes)
|
|
||||||
return
|
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"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
UnimplementedErr = errors.New("unimplemented")
|
||||||
|
)
|
||||||
|
|
||||||
type Direction int
|
type Direction int
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -45,6 +49,17 @@ const (
|
|||||||
Client
|
Client
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func (a Actor) String() string {
|
||||||
|
switch a {
|
||||||
|
case Servee:
|
||||||
|
return "Servee"
|
||||||
|
case Client:
|
||||||
|
return "Client"
|
||||||
|
default:
|
||||||
|
return "Unknown"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (a Actor) SendDirection() Direction {
|
func (a Actor) SendDirection() Direction {
|
||||||
switch a {
|
switch a {
|
||||||
case Servee:
|
case Servee:
|
||||||
@@ -67,12 +82,6 @@ func (a Actor) ReceiveDirection() Direction {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type PacketIdentifier struct {
|
|
||||||
Direction Direction
|
|
||||||
State State
|
|
||||||
Name string
|
|
||||||
}
|
|
||||||
|
|
||||||
type (
|
type (
|
||||||
ToDo struct{}
|
ToDo struct{}
|
||||||
RestBuffer []byte
|
RestBuffer []byte
|
||||||
@@ -213,6 +222,15 @@ type EncodeDecodeAble interface {
|
|||||||
Decode(r io.Reader) (err error)
|
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 PacketInfo struct {
|
||||||
Type EncodeDecodeAble
|
Type EncodeDecodeAble
|
||||||
Name string
|
Name string
|
||||||
@@ -221,3 +239,31 @@ type PacketInfo struct {
|
|||||||
PacketId int32
|
PacketId int32
|
||||||
ProtocolVersion 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 {
|
type PacketInfo struct {
|
||||||
TName, Name, Direction, State, PacketId, ProtocolVersion, MinecraftVersion string
|
TName, Name, Direction, State, PacketId, ProtocolVersion, MinecraftVersion string
|
||||||
|
PacketDef any
|
||||||
}
|
}
|
||||||
|
|
||||||
func GeneratePacketInfoFile(versions []string, packetInfos []PacketInfo) (err error) {
|
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, ".", "_")
|
vUnderscore := "v" + strings.ReplaceAll(p.MinecraftVersion, ".", "_")
|
||||||
typeName := p.TName
|
typeName := p.TName
|
||||||
var typeExpr ast.Expr
|
var typeExpr ast.Expr
|
||||||
if typeName == "struct{}" {
|
if p.PacketDef == "void" {
|
||||||
typeExpr = &ast.StructType{Fields: &ast.FieldList{}}
|
typeExpr = Selector("proto_base", "Void")
|
||||||
} else if strings.HasPrefix(typeName, "proto_base.") {
|
|
||||||
typeExpr = Selector("proto_base", strings.TrimPrefix(typeName, "proto_base."))
|
|
||||||
} else {
|
} else {
|
||||||
typeExpr = Selector(vUnderscore, typeName)
|
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("Type"), AddrOf(CompLit(typeExpr, nil))),
|
||||||
KeyValueExpr(Ident("Name"), StrLit(p.Name)),
|
KeyValueExpr(Ident("Name"), StrLit(p.Name)),
|
||||||
KeyValueExpr(Ident("Direction"), Selector("proto_base", p.Direction)),
|
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("PacketId"), NumLit(int(packetId))),
|
||||||
KeyValueExpr(Ident("ProtocolVersion"), NumLit(protocolVersion)),
|
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)))
|
AppendDecl(f, VarValues("Packets", CompLit(Slice(Selector("proto_base", "PacketInfo")), packetInfoExprs)))
|
||||||
out, err := os.Create("proto_generated/packet_info.go")
|
out, err := os.Create("proto_generated/packet_info.go")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
+22
-18
@@ -38,6 +38,12 @@ type ContainerStackEntry struct {
|
|||||||
VarToSet ast.Expr
|
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 {
|
type Generator struct {
|
||||||
packetInfos []PacketInfo
|
packetInfos []PacketInfo
|
||||||
|
|
||||||
@@ -60,7 +66,6 @@ type Generator struct {
|
|||||||
Depth int
|
Depth int
|
||||||
Declared []string
|
Declared []string
|
||||||
ContainerStack []ContainerStackEntry
|
ContainerStack []ContainerStackEntry
|
||||||
VtsStack []ast.Expr
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (g *Generator) Decl(name string, t token.Token, e 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
|
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) {
|
func (g *Generator) VisitType(data any) (e ast.Expr, err error) {
|
||||||
tName, tData, err := ParseType(data)
|
tName, tData, err := ParseType(data)
|
||||||
if err != nil {
|
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) {
|
func (g *Generator) GenerateProtocol(protocol Protocol, version string) (err error) {
|
||||||
versionData, err := data.LookUpProtocolVersionByName(version)
|
versionData, err := data.LookUpVersionByName(version)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -271,7 +270,8 @@ func (g *Generator) GenerateProtocol(protocol Protocol, version string) (err err
|
|||||||
v := protocol.Types.Types[k]
|
v := protocol.Types.Types[k]
|
||||||
if strings.Contains(k, "packet") {
|
if strings.Contains(k, "packet") {
|
||||||
delete(protocol.Types.Types, k)
|
delete(protocol.Types.Types, k)
|
||||||
for prefix, types := range prefixTypeMap {
|
for _, prefix := range OrderedKeys(prefixTypeMap) {
|
||||||
|
types := prefixTypeMap[prefix]
|
||||||
if prefix == "" {
|
if prefix == "" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -280,32 +280,36 @@ func (g *Generator) GenerateProtocol(protocol Protocol, version string) (err err
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for prefix, types := range prefixTypeMap {
|
for _, prefix := range OrderedKeys(prefixTypeMap) {
|
||||||
for k, v := range types.Types.Types {
|
types := prefixTypeMap[prefix]
|
||||||
|
for _, k := range OrderedKeys(types.Types.Types) {
|
||||||
|
typeData := types.Types.Types[k]
|
||||||
if k != "packet" {
|
if k != "packet" {
|
||||||
continue
|
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)
|
packetIdsStrings := AssertAndConvertMapValues[string](packetIds)
|
||||||
packetIdsRev := ReverseMap(packetIdsStrings)
|
packetIdsRev := ReverseMap(packetIdsStrings)
|
||||||
v := v.([]any)[1].([]any)[1].(map[string]any)["type"].([]any)[1].(map[string]any)["fields"].(map[string]any)
|
v := typeData.([]any)[1].([]any)[1].(map[string]any)["type"].([]any)[1].(map[string]any)["fields"].(map[string]any)
|
||||||
for k2, v2 := range v {
|
for _, k2 := range OrderedKeys(v) {
|
||||||
v2 := v2.(string)
|
v2 := v[k2].(string)
|
||||||
typeName := prefix + CamelCase(v2)
|
typeName := prefix + CamelCase(v2)
|
||||||
g.packetInfos = append(g.packetInfos, PacketInfo{
|
g.packetInfos = append(g.packetInfos, PacketInfo{
|
||||||
|
PacketDef: v2,
|
||||||
TName: typeName,
|
TName: typeName,
|
||||||
Name: k2,
|
Name: k2,
|
||||||
Direction: types.Direction,
|
Direction: types.Direction,
|
||||||
State: types.State,
|
State: types.State,
|
||||||
PacketId: packetIdsRev[k2],
|
PacketId: packetIdsRev[k2],
|
||||||
ProtocolVersion: strconv.Itoa(versionData.Version),
|
ProtocolVersion: strconv.Itoa(int(versionData.Version)),
|
||||||
MinecraftVersion: version,
|
MinecraftVersion: version,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for prefix, types := range prefixTypeMap {
|
for _, prefix := range OrderedKeys(prefixTypeMap) {
|
||||||
|
types := prefixTypeMap[prefix]
|
||||||
err = g.GenerateTypes(prefix, types.Types)
|
err = g.GenerateTypes(prefix, types.Types)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
@@ -378,7 +382,7 @@ func GenerateVersions(versions []string) (err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
err := GenerateVersions([]string{"1.21.8"})
|
err := GenerateVersions([]string{"1.21.8", "1.21.9", "1.21.11"})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,10 +6,11 @@ import (
|
|||||||
"go/ast"
|
"go/ast"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/admin-else/strom/proto_generator/protodef"
|
||||||
"github.com/go-viper/mapstructure/v2"
|
"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, "/")
|
parts := strings.Split(compareTo, "/")
|
||||||
downPrefixCount := 0
|
downPrefixCount := 0
|
||||||
for _, part := range parts {
|
for _, part := range parts {
|
||||||
@@ -19,12 +20,12 @@ func (g *Generator) ParseCompareTo(compareTo string) (e ast.Expr, err error) {
|
|||||||
}
|
}
|
||||||
parts = parts[downPrefixCount:]
|
parts = parts[downPrefixCount:]
|
||||||
startingPoint := g.ContainerStack[len(g.ContainerStack)-downPrefixCount-1]
|
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 ParseCompareToLegacy(compareTo, varToSet)
|
||||||
return
|
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)
|
tName, tData, err := ParseType(data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
@@ -37,12 +38,8 @@ func (g *Generator) VisitCompareTo(parts []string, inExpr ast.Expr, data any) (e
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func ContainerCompareTo(g *Generator, parts []string, inExpr ast.Expr, dataRaw any) (e ast.Expr, err error) {
|
func ContainerCompareTo(g *Generator, parts []string, inExpr ast.Expr, dataRaw any) (e ast.Expr, cet CaseExprType, err error) {
|
||||||
var data []struct {
|
var data protodef.Container
|
||||||
Name string
|
|
||||||
Type any
|
|
||||||
Anon bool
|
|
||||||
}
|
|
||||||
err = mapstructure.Decode(dataRaw, &data)
|
err = mapstructure.Decode(dataRaw, &data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
@@ -62,15 +59,40 @@ func ContainerCompareTo(g *Generator, parts []string, inExpr ast.Expr, dataRaw a
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func ReturnInputCompareTo(_ *Generator, _ []string, inExpr ast.Expr, _ any) (e ast.Expr, err error) {
|
func ReturnInputCompareTo(_ *Generator, _ []string, inExpr ast.Expr, _ any) (e ast.Expr, cet CaseExprType, err error) {
|
||||||
return inExpr, nil
|
return inExpr, CaseExprTypeUnset, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func BitflagsCompareTo(_ *Generator, parts []string, inExpr ast.Expr, dataRaw any) (e ast.Expr, err error) {
|
func BitfieldCompareTo(_ *Generator, parts []string, inExpr ast.Expr, dataRaw any) (e ast.Expr, cet CaseExprType, err error) {
|
||||||
var data struct {
|
var data protodef.BitField
|
||||||
Flags []string
|
err = mapstructure.Decode(dataRaw, &data)
|
||||||
Type any
|
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)
|
err = mapstructure.Decode(dataRaw, &data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
@@ -98,7 +120,7 @@ func (g *Generator) RegisterCompareToNatives() {
|
|||||||
"bool": ReturnInputCompareTo,
|
"bool": ReturnInputCompareTo,
|
||||||
"mapper": ReturnInputCompareTo,
|
"mapper": ReturnInputCompareTo,
|
||||||
"varint": ReturnInputCompareTo,
|
"varint": ReturnInputCompareTo,
|
||||||
"bitfield": ReturnInputCompareTo,
|
"bitfield": BitfieldCompareTo,
|
||||||
"u8": ReturnInputCompareTo,
|
"u8": ReturnInputCompareTo,
|
||||||
"i8": ReturnInputCompareTo,
|
"i8": ReturnInputCompareTo,
|
||||||
"bitflags": BitflagsCompareTo,
|
"bitflags": BitflagsCompareTo,
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"slices"
|
"slices"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/admin-else/strom/proto_generator/protodef"
|
||||||
"github.com/go-viper/mapstructure/v2"
|
"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) {
|
func ContainerDecoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||||
var data []struct {
|
var data protodef.Container
|
||||||
Name string
|
|
||||||
Type any
|
|
||||||
Anon bool
|
|
||||||
}
|
|
||||||
err = mapstructure.Decode(dataRaw, &data)
|
err = mapstructure.Decode(dataRaw, &data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
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) {
|
func ArrayDecoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||||
var data struct {
|
var data protodef.Array
|
||||||
CountType any
|
|
||||||
Count string
|
|
||||||
Type any
|
|
||||||
}
|
|
||||||
lName := "l" + CamelCase(name)
|
lName := "l" + CamelCase(name)
|
||||||
err = mapstructure.Decode(dataRaw, &data)
|
err = mapstructure.Decode(dataRaw, &data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -136,7 +129,7 @@ func ArrayDecoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s
|
|||||||
if err == nil {
|
if err == nil {
|
||||||
e = NumLit(n)
|
e = NumLit(n)
|
||||||
} else {
|
} else {
|
||||||
e, err = g.ParseCompareTo(data.Count)
|
e, _, err = g.ParseCompareTo(data.Count)
|
||||||
}
|
}
|
||||||
s2 = append(s2, Assign121(Ident(lName), e))
|
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) {
|
func TypeForwardDecoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||||
var data struct {
|
var data protodef.TypeForward
|
||||||
Type string
|
|
||||||
}
|
|
||||||
if err = mapstructure.Decode(dataRaw, &data); err != nil {
|
if err = mapstructure.Decode(dataRaw, &data); err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
return g.VisitDecoder(varToSet, data.Type, name)
|
return g.VisitDecoder(varToSet, data.Type, name)
|
||||||
}
|
}
|
||||||
|
|
||||||
var DontStringify = []string{"true", "false"}
|
var BooleanValues = []string{"true", "false"}
|
||||||
|
|
||||||
// CaseExprType This exists to fix this
|
// CaseExprType This exists to fix this
|
||||||
// "switch",
|
// "switch",
|
||||||
@@ -194,13 +185,22 @@ var DontStringify = []string{"true", "false"}
|
|||||||
// "default": [
|
// "default": [
|
||||||
//
|
//
|
||||||
// Protodef is best!!!
|
// 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
|
type CaseExprType int
|
||||||
|
|
||||||
const (
|
const (
|
||||||
CaseExprTypeUnset CaseExprType = iota
|
CaseExprTypeUnset CaseExprType = iota
|
||||||
CaseExprTypeNumber
|
CaseExprTypeNumber
|
||||||
CaseExprTypeSpecial
|
CaseExprTypeBool
|
||||||
CaseExprTypeString
|
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) {
|
func MultiTypeFix(s string, t *CaseExprType) (e ast.Expr) {
|
||||||
@@ -210,9 +210,9 @@ func MultiTypeFix(s string, t *CaseExprType) (e ast.Expr) {
|
|||||||
err = nil
|
err = nil
|
||||||
e = NumLit(n)
|
e = NumLit(n)
|
||||||
ct = CaseExprTypeNumber
|
ct = CaseExprTypeNumber
|
||||||
} else if slices.Contains(DontStringify, s) {
|
} else if slices.Contains(BooleanValues, s) {
|
||||||
e = Ident(s)
|
e = Ident(s)
|
||||||
ct = CaseExprTypeSpecial
|
ct = CaseExprTypeBool
|
||||||
} else {
|
} else {
|
||||||
e = StrLit(s)
|
e = StrLit(s)
|
||||||
ct = CaseExprTypeString
|
ct = CaseExprTypeString
|
||||||
@@ -222,27 +222,32 @@ func MultiTypeFix(s string, t *CaseExprType) (e ast.Expr) {
|
|||||||
*t = ct
|
*t = ct
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if *t != ct {
|
if *t == ct {
|
||||||
e = nil
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ct == CaseExprTypeNumber && *t == CaseExprTypeOnlyBool {
|
||||||
|
if s == "0" {
|
||||||
|
e = Ident("false")
|
||||||
|
} else {
|
||||||
|
e = Ident("true")
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
e = nil
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func SwitchDecoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
func SwitchDecoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||||
var data struct {
|
var data protodef.Switch
|
||||||
CompareTo string
|
|
||||||
Fields map[string]any
|
|
||||||
Default any
|
|
||||||
}
|
|
||||||
err = mapstructure.Decode(dataRaw, &data)
|
err = mapstructure.Decode(dataRaw, &data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
compareToExpr, err := g.ParseCompareTo(data.CompareTo)
|
compareToExpr, cet, err := g.ParseCompareTo(data.CompareTo)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
cet := CaseExprTypeUnset
|
|
||||||
for _, fName := range OrderedKeys(data.Fields) {
|
for _, fName := range OrderedKeys(data.Fields) {
|
||||||
fType := data.Fields[fName]
|
fType := data.Fields[fName]
|
||||||
e := MultiTypeFix(fName, &cet)
|
e := MultiTypeFix(fName, &cet)
|
||||||
@@ -258,7 +263,7 @@ func SwitchDecoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s
|
|||||||
s1 := VarStmt(tName, tType)
|
s1 := VarStmt(tName, tType)
|
||||||
s3 := Assign121(varToSet, Ident(tName))
|
s3 := Assign121(varToSet, Ident(tName))
|
||||||
var caseDecodeValueStmts []ast.Stmt
|
var caseDecodeValueStmts []ast.Stmt
|
||||||
caseDecodeValueStmts, err = g.VisitDecoder(Ident(tName), fType, name)
|
caseDecodeValueStmts, err = g.VisitDecoder(Ident(tName), fType, tName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
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) {
|
func MapperDecoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||||
var data struct {
|
var data protodef.Mapper
|
||||||
Mappings map[string]string
|
|
||||||
Type any
|
|
||||||
}
|
|
||||||
err = mapstructure.Decode(dataRaw, &data)
|
err = mapstructure.Decode(dataRaw, &data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
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) {
|
func BufferDecoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||||
var data struct {
|
var data protodef.Buffer
|
||||||
Count int
|
|
||||||
CountType any
|
|
||||||
}
|
|
||||||
err = mapstructure.Decode(dataRaw, &data)
|
err = mapstructure.Decode(dataRaw, &data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
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) {
|
func BitFieldDecoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||||
var data []struct {
|
var data protodef.BitField
|
||||||
Name string
|
|
||||||
Singed bool
|
|
||||||
Size int
|
|
||||||
}
|
|
||||||
err = mapstructure.Decode(dataRaw, &data)
|
err = mapstructure.Decode(dataRaw, &data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
@@ -386,24 +381,74 @@ func BitFieldDecoder(g *Generator, varToSet ast.Expr, dataRaw any, name string)
|
|||||||
for _, field := range data {
|
for _, field := range data {
|
||||||
totalSize += field.Size
|
totalSize += field.Size
|
||||||
}
|
}
|
||||||
p, err := TotalBitfieldSizeToProtodefName(totalSize)
|
packedTypeProtodef, err := BitSizeToProtodef(totalSize, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
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) {
|
func RegistryEntryHolderSetDecoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||||
var data struct {
|
var data protodef.RegistryEntryHolderSet
|
||||||
Base struct {
|
|
||||||
Name string
|
|
||||||
Type any
|
|
||||||
}
|
|
||||||
Otherwise struct {
|
|
||||||
Name string
|
|
||||||
Type any
|
|
||||||
}
|
|
||||||
}
|
|
||||||
err = mapstructure.Decode(dataRaw, &data)
|
err = mapstructure.Decode(dataRaw, &data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
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) {
|
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)
|
err = mapstructure.Decode(dataRaw, &data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
@@ -532,6 +577,7 @@ func (g *Generator) RegisterDecoderNatives() {
|
|||||||
"varlong": VarLongDecoder,
|
"varlong": VarLongDecoder,
|
||||||
"anonymousNbt": DefaultDecoder,
|
"anonymousNbt": DefaultDecoder,
|
||||||
"anonOptionalNbt": DefaultDecoder, // I have no idea what the difference is between these two
|
"anonOptionalNbt": DefaultDecoder, // I have no idea what the difference is between these two
|
||||||
|
"lpVec3": ToDoDecoder,
|
||||||
"UUID": UUIDDecoder,
|
"UUID": UUIDDecoder,
|
||||||
"restBuffer": DefaultDecoder,
|
"restBuffer": DefaultDecoder,
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,10 @@ package main
|
|||||||
import (
|
import (
|
||||||
"go/ast"
|
"go/ast"
|
||||||
"go/token"
|
"go/token"
|
||||||
|
"slices"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/admin-else/strom/proto_generator/protodef"
|
||||||
"github.com/go-viper/mapstructure/v2"
|
"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) {
|
func ContainerEncoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||||
var data []struct {
|
var data protodef.Container
|
||||||
Name string
|
|
||||||
Type any
|
|
||||||
Anon bool
|
|
||||||
}
|
|
||||||
err = mapstructure.Decode(dataRaw, &data)
|
err = mapstructure.Decode(dataRaw, &data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
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) {
|
func ArrayEncoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||||
var data struct {
|
var data protodef.Array
|
||||||
CountType any
|
|
||||||
Count string
|
|
||||||
Type any
|
|
||||||
}
|
|
||||||
err = mapstructure.Decode(dataRaw, &data)
|
err = mapstructure.Decode(dataRaw, &data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
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) {
|
func BufferEncoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||||
var data struct {
|
var data protodef.Buffer
|
||||||
Count int
|
|
||||||
CountType any
|
|
||||||
}
|
|
||||||
err = mapstructure.Decode(dataRaw, &data)
|
err = mapstructure.Decode(dataRaw, &data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
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) {
|
func BitFieldEncoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||||
var data []struct {
|
var data protodef.BitField
|
||||||
Name string
|
|
||||||
Singed bool
|
|
||||||
Size int
|
|
||||||
}
|
|
||||||
err = mapstructure.Decode(dataRaw, &data)
|
err = mapstructure.Decode(dataRaw, &data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
@@ -159,28 +147,59 @@ func BitFieldEncoder(g *Generator, varToSet ast.Expr, dataRaw any, name string)
|
|||||||
for _, field := range data {
|
for _, field := range data {
|
||||||
totalSize += field.Size
|
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 {
|
if err != nil {
|
||||||
return
|
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) {
|
func SwitchEncoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||||
var data struct {
|
var data protodef.Switch
|
||||||
CompareTo string
|
|
||||||
Fields map[string]any
|
|
||||||
Default any
|
|
||||||
}
|
|
||||||
err = mapstructure.Decode(dataRaw, &data)
|
err = mapstructure.Decode(dataRaw, &data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
compareToExpr, err := g.ParseCompareTo(data.CompareTo)
|
compareToExpr, cet, err := g.ParseCompareTo(data.CompareTo)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
cet := CaseExprTypeUnset
|
|
||||||
for _, fName := range OrderedKeys(data.Fields) {
|
for _, fName := range OrderedKeys(data.Fields) {
|
||||||
fType := data.Fields[fName]
|
fType := data.Fields[fName]
|
||||||
e := MultiTypeFix(fName, &cet)
|
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) {
|
func TypeForwardEncoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||||
var data struct {
|
var data protodef.TypeForward
|
||||||
Type string
|
|
||||||
}
|
|
||||||
if err = mapstructure.Decode(dataRaw, &data); err != nil {
|
if err = mapstructure.Decode(dataRaw, &data); err != nil {
|
||||||
return
|
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) {
|
func MapperEncoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||||
var data struct {
|
var data protodef.Mapper
|
||||||
Mappings map[string]string
|
|
||||||
Type any
|
|
||||||
}
|
|
||||||
err = mapstructure.Decode(dataRaw, &data)
|
err = mapstructure.Decode(dataRaw, &data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
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) {
|
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)
|
err = mapstructure.Decode(dataRaw, &data)
|
||||||
otherwiseType, err := g.VisitType(data.Otherwise.Type)
|
otherwiseType, err := g.VisitType(data.Otherwise.Type)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -359,6 +373,7 @@ func (g *Generator) RegisterEncoderNatives() {
|
|||||||
"anonOptionalNbt": DefaultEncoder, // I have no idea what the difference is between these two
|
"anonOptionalNbt": DefaultEncoder, // I have no idea what the difference is between these two
|
||||||
"UUID": UUIDEncoder,
|
"UUID": UUIDEncoder,
|
||||||
"restBuffer": DefaultEncoder,
|
"restBuffer": DefaultEncoder,
|
||||||
|
"lpVec3": ToDoEncoder,
|
||||||
"string": StringEncoder,
|
"string": StringEncoder,
|
||||||
|
|
||||||
"f32": SimpleTypeEncoder,
|
"f32": SimpleTypeEncoder,
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"go/ast"
|
"go/ast"
|
||||||
|
|
||||||
|
"github.com/admin-else/strom/proto_generator/protodef"
|
||||||
"github.com/go-viper/mapstructure/v2"
|
"github.com/go-viper/mapstructure/v2"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -27,7 +28,8 @@ func VisitContainerType(g *Generator, dataRaw any) (ast.Expr, error) {
|
|||||||
|
|
||||||
s := NewStruct()
|
s := NewStruct()
|
||||||
for _, field := range data {
|
for _, field := range data {
|
||||||
t, err := g.VisitType(field.Type)
|
var t ast.Expr
|
||||||
|
t, err = g.VisitType(field.Type)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -59,13 +61,16 @@ func VisitBufferType(_ *Generator, dataRaw any) (e ast.Expr, err error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func VisitArrayTypeVisitorType(g *Generator, dataRaw any) (ast.Expr, error) {
|
func VisitArrayTypeVisitorType(g *Generator, dataRaw any) (e ast.Expr, err error) {
|
||||||
var data struct {
|
var data struct {
|
||||||
CountType any
|
CountType any
|
||||||
Type any
|
Type any
|
||||||
}
|
}
|
||||||
must(mapstructure.Decode(dataRaw, &data))
|
err = mapstructure.Decode(dataRaw, &data)
|
||||||
e, err := g.VisitType(data.Type)
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
e, err = g.VisitType(data.Type)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -90,15 +95,24 @@ func VisitOptionType(g *Generator, dataRaw any) (e ast.Expr, err error) {
|
|||||||
return
|
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 {
|
if totalSize <= 8 {
|
||||||
e = "u8"
|
e += "8"
|
||||||
} else if totalSize <= 16 {
|
} else if totalSize <= 16 {
|
||||||
e = "u16"
|
e += "16"
|
||||||
} else if totalSize <= 32 {
|
} else if totalSize <= 32 {
|
||||||
e = "u32"
|
e += "32"
|
||||||
} else if totalSize <= 64 {
|
} else if totalSize <= 64 {
|
||||||
e = "u64"
|
e += "64"
|
||||||
} else {
|
} else {
|
||||||
err = errors.New("bitfield size too large")
|
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) {
|
func VisitBitFieldType(g *Generator, dataRaw any) (e ast.Expr, err error) {
|
||||||
var data []struct {
|
var data protodef.BitField
|
||||||
Name string
|
|
||||||
Singed bool
|
|
||||||
Size int
|
|
||||||
}
|
|
||||||
err = mapstructure.Decode(dataRaw, &data)
|
err = mapstructure.Decode(dataRaw, &data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
totalSize := 0
|
ret := NewStruct()
|
||||||
for _, field := range data {
|
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
|
e = ret
|
||||||
p, err := TotalBitfieldSizeToProtodefName(totalSize)
|
return
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
return g.VisitType(p)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func VisitBitFlagsType(g *Generator, dataRaw any) (e ast.Expr, err error) {
|
func VisitBitFlagsType(g *Generator, dataRaw any) (e ast.Expr, err error) {
|
||||||
@@ -194,5 +210,6 @@ func (g *Generator) RegisterNatives() {
|
|||||||
"bitflags": VisitBitFlagsType,
|
"bitflags": VisitBitFlagsType,
|
||||||
"topBitSetTerminatedArray": VisitToDoType,
|
"topBitSetTerminatedArray": VisitToDoType,
|
||||||
"todo": VisitToDoType,
|
"todo": VisitToDoType,
|
||||||
|
"lpVec3": VisitToDoType,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -95,7 +95,7 @@ func NumLit(n int) *ast.BasicLit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NumLitHex(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 {
|
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 {
|
func Exprs(exprs ...ast.Expr) []ast.Expr {
|
||||||
return exprs
|
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 {
|
func Nil() ast.Expr {
|
||||||
return Ident("nil")
|
return Ident("nil")
|
||||||
}
|
}
|
||||||
@@ -479,3 +503,25 @@ func BinAnd(lhs, rhs ast.Expr) *ast.BinaryExpr {
|
|||||||
Y: rhs,
|
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
|
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
|
return ret
|
||||||
}
|
}
|
||||||
|
|
||||||
func must(err error) {
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func PopFront[T any](s []T) (T, []T, bool) {
|
func PopFront[T any](s []T) (T, []T, bool) {
|
||||||
if len(s) == 0 {
|
if len(s) == 0 {
|
||||||
var zero T
|
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 (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package server_modules
|
package server
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
@@ -15,7 +15,7 @@ import (
|
|||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
)
|
)
|
||||||
|
|
||||||
var StatusServedError = errors.New("status served")
|
var StatusServedErr = errors.New("status served")
|
||||||
|
|
||||||
var UnexpectedStatusRequest = UnexpectedNextStateError{proto_base.Status}
|
var UnexpectedStatusRequest = UnexpectedNextStateError{proto_base.Status}
|
||||||
|
|
||||||
@@ -32,8 +32,6 @@ func (u UnexpectedNextStateError) Error() string {
|
|||||||
return fmt.Sprintf("unexpected next state: %v", u.NextState)
|
return fmt.Sprintf("unexpected next state: %v", u.NextState)
|
||||||
}
|
}
|
||||||
|
|
||||||
var IncompatibleProtocolVersionError = fmt.Errorf("incompatible protocol version")
|
|
||||||
|
|
||||||
type LoginServer struct {
|
type LoginServer struct {
|
||||||
*proto.Conn
|
*proto.Conn
|
||||||
//OnlineMode bool FIXME: implement this
|
//OnlineMode bool FIXME: implement this
|
||||||
@@ -41,7 +39,7 @@ type LoginServer struct {
|
|||||||
ServerPort uint16
|
ServerPort uint16
|
||||||
Requested NameAndUUID
|
Requested NameAndUUID
|
||||||
Given *NameAndUUID
|
Given *NameAndUUID
|
||||||
CompressionThreshold int32
|
CompressionThreshold int32 //FIXME: implement this
|
||||||
Status []byte
|
Status []byte
|
||||||
CompatibleVersions []int32
|
CompatibleVersions []int32
|
||||||
}
|
}
|
||||||
@@ -51,16 +49,20 @@ func (l *LoginServer) OnHandshake(packet *v1_21_8.HandshakingToServerPacketSetPr
|
|||||||
l.ServerHost = packet.ServerHost
|
l.ServerHost = packet.ServerHost
|
||||||
l.ServerPort = packet.ServerPort
|
l.ServerPort = packet.ServerPort
|
||||||
|
|
||||||
if len(l.CompatibleVersions) != 0 {
|
if packet.NextState == int32(proto_base.Status) && l.Status != nil {
|
||||||
if !slices.Contains(l.CompatibleVersions, packet.ProtocolVersion) {
|
return
|
||||||
err = IncompatibleProtocolVersionError
|
|
||||||
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)}
|
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
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,7 +76,7 @@ func (l *LoginServer) OnStatusPing(packet *v1_21_8.StatusToServerPacketPing) (er
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
return event.HandlerDoneErr{Return: StatusServedError}
|
return event.HandlerDoneErr{Return: StatusServedErr}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *LoginServer) SetCompressionThreshold(threshold int32) (err error) {
|
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) {
|
func (l *LoginServer) OnLoginStart(packet *v1_21_8.LoginToServerPacketLoginStart) (err error) {
|
||||||
l.Requested = NameAndUUID{packet.Username, packet.PlayerUUID}
|
l.Requested = NameAndUUID{packet.Username, packet.PlayerUUID}
|
||||||
//err = l.SetCompressionThreshold(l.CompressionThreshold)
|
|
||||||
//if err != nil {
|
|
||||||
// return
|
|
||||||
//}
|
|
||||||
if l.Given == nil {
|
if l.Given == nil {
|
||||||
l.Given = &l.Requested
|
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) {
|
func (l *LoginServer) OnDefault(event event.Unhandled) (err error) {
|
||||||
err = fmt.Errorf("unexpected event during login: %#v", event)
|
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
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -153,19 +142,15 @@ func WithStatus(response StatusResponse) LoginServerSetting {
|
|||||||
return WithRawStatus(status)
|
return WithRawStatus(status)
|
||||||
}
|
}
|
||||||
|
|
||||||
func WithCompatibleVersion(versions int32) LoginServerSetting {
|
|
||||||
return WithCompatibleVersions([]int32{versions})
|
|
||||||
}
|
|
||||||
|
|
||||||
func WithCompatibleVersionsRange(start, end int32) LoginServerSetting {
|
func WithCompatibleVersionsRange(start, end int32) LoginServerSetting {
|
||||||
var versions []int32
|
var versions []int32
|
||||||
for i := start; i <= end; i++ {
|
for i := start; i <= end; i++ {
|
||||||
versions = append(versions, 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) {
|
return func(s *LoginServer) {
|
||||||
s.CompatibleVersions = versions
|
s.CompatibleVersions = versions
|
||||||
}
|
}
|
||||||
@@ -173,10 +158,16 @@ func WithCompatibleVersions(versions []int32) LoginServerSetting {
|
|||||||
|
|
||||||
func ServeLogin(c *proto.Conn, settings ...LoginServerSetting) (ret *LoginServer, err error) {
|
func ServeLogin(c *proto.Conn, settings ...LoginServerSetting) (ret *LoginServer, err error) {
|
||||||
ret = &LoginServer{Conn: c}
|
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 {
|
for _, s := range settings {
|
||||||
s(ret)
|
s(ret)
|
||||||
}
|
}
|
||||||
ret.CompressionThreshold = 256
|
ret.CompressionThreshold = 256
|
||||||
err = ret.Start(ret)
|
err = ret.Start()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
type SchematicServer interface {
|
||||||
|
}
|
||||||
+24
-6
@@ -1,12 +1,12 @@
|
|||||||
package server
|
package server
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
"github.com/admin-else/strom/proto"
|
"github.com/admin-else/strom/proto"
|
||||||
"github.com/admin-else/strom/proto_base"
|
"github.com/admin-else/strom/proto_base"
|
||||||
"github.com/admin-else/strom/server/server_modules"
|
|
||||||
"github.com/admin-else/strom/text"
|
"github.com/admin-else/strom/text"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -14,7 +14,7 @@ func Servee(c net.Conn) (ret *proto.Conn) {
|
|||||||
ret = &proto.Conn{}
|
ret = &proto.Conn{}
|
||||||
_ = ret.SetVersion("1.21.8") // cant fail
|
_ = ret.SetVersion("1.21.8") // cant fail
|
||||||
ret.SetState(proto_base.Handshaking)
|
ret.SetState(proto_base.Handshaking)
|
||||||
ret.CompressionThreshold = -1
|
ret.SetCompressionThreshold(-1)
|
||||||
ret.Actor = proto_base.Servee
|
ret.Actor = proto_base.Servee
|
||||||
ret.Conn = c
|
ret.Conn = c
|
||||||
ret.R = c
|
ret.R = c
|
||||||
@@ -22,17 +22,32 @@ func Servee(c net.Conn) (ret *proto.Conn) {
|
|||||||
return
|
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)
|
c := Servee(cNet)
|
||||||
|
defer c.Close()
|
||||||
h, err := factory(c)
|
h, err := factory(c)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
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
|
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)
|
l, err := net.Listen("tcp", listenAddr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
@@ -63,8 +78,11 @@ func StartServerWithOnConn(listenAddr string, onConn func(c *proto.Conn) (err er
|
|||||||
defer c.Close()
|
defer c.Close()
|
||||||
connErr := onConn(c)
|
connErr := onConn(c)
|
||||||
if connErr != nil {
|
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())
|
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 {
|
if connErr != nil {
|
||||||
slog.Error("Error while kicking client", "error", connErr, "client", c.Conn.RemoteAddr())
|
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"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/admin-else/strom/nbt"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Component represents a Minecraft text component.
|
// Component represents a Minecraft text component.
|
||||||
@@ -60,11 +62,56 @@ func (c *Component) MarshalJSON() ([]byte, error) {
|
|||||||
if c.isSimpleText() {
|
if c.isSimpleText() {
|
||||||
return json.Marshal(c.Text)
|
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
|
type Alias Component
|
||||||
|
|
||||||
return json.Marshal(Alias(*c))
|
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 {
|
func (c *Component) isSimpleText() bool {
|
||||||
return c.Text != "" &&
|
return c.Text != "" &&
|
||||||
c.Bold == nil && c.Italic == nil && c.Underlined == nil && c.Strikethrough == nil && c.Obfuscated == nil &&
|
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()
|
m["separator"] = c.Separator.ToNBT()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if c.hasFormattingButNoContent() {
|
||||||
|
m["text"] = ""
|
||||||
|
}
|
||||||
|
|
||||||
return m
|
return m
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -538,3 +589,14 @@ func (c *Component) writePretty(sb *strings.Builder) {
|
|||||||
extra.writePretty(sb)
|
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) {
|
func TestPrettyF(t *testing.T) {
|
||||||
got := PrettyF("Hello §b%s", "World")
|
got := PrettyF("Hello §b%s", "World")
|
||||||
want := Component{
|
want := &Component{
|
||||||
Text: "Hello ",
|
Text: "Hello ",
|
||||||
Extra: []Component{
|
Extra: []Component{
|
||||||
{Text: "World", Color: "aqua"},
|
{Text: "World", Color: "aqua"},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
if !reflect.DeepEqual(got, want) {
|
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
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
"github.com/admin-else/strom/api"
|
"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/event"
|
||||||
"github.com/admin-else/strom/proto"
|
"github.com/admin-else/strom/proto"
|
||||||
"github.com/admin-else/strom/proto_base"
|
"github.com/admin-else/strom/proto_base"
|
||||||
"github.com/admin-else/strom/proto_generated/v1_21_8"
|
"github.com/admin-else/strom/proto_generated/v1_21_8"
|
||||||
"github.com/admin-else/strom/server"
|
"github.com/admin-else/strom/server"
|
||||||
"github.com/admin-else/strom/server/server_modules"
|
|
||||||
"github.com/admin-else/strom/text"
|
"github.com/admin-else/strom/text"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -35,11 +34,11 @@ func (p *ProxyClient) OnCycle(_ event.Tick) (err error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *ProxyClient) OnStart(_ event.OnStart) (err error) {
|
func (p *ProxyClient) OnStart() (err error) {
|
||||||
return
|
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})
|
err = p.OnDefault(event.Unhandled{Val: packet})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
@@ -66,7 +65,7 @@ func (p *Proxy) OnCycle(_ event.Tick) (err error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Proxy) OnStart(_ event.OnStart) (err error) {
|
func (p *Proxy) OnStart() (err error) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,7 +79,7 @@ func (p *Proxy) OnFinishConfiguration(packet *v1_21_8.ConfigurationToServerPacke
|
|||||||
return
|
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})
|
err = p.OnDefault(event.Unhandled{Val: packet})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
@@ -102,58 +101,51 @@ import (
|
|||||||
func TestFailedPacket%10X(t *testing.T) {
|
func TestFailedPacket%10X(t *testing.T) {
|
||||||
p := v1_21_8.Play%vPacket{}
|
p := v1_21_8.Play%vPacket{}
|
||||||
b := bytes.NewBuffer(%#v)
|
b := bytes.NewBuffer(%#v)
|
||||||
p, err := p.Decode(b)
|
err := p.Decode(b)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
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)
|
hUntrimmed := sha256.Sum256(packet.Data)
|
||||||
h := hUntrimmed[:8]
|
h := hUntrimmed[:8]
|
||||||
f, err := os.Create(fmt.Sprintf(".failed_packets/%v_%10x_test.go", len(packet.Data), h))
|
f, err := os.Create(fmt.Sprintf(".failed_packets/%v_%10x_test.go", len(packet.Data), h))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//goland:noinspection GoUnhandledErrorResult
|
||||||
defer f.Close()
|
defer f.Close()
|
||||||
_, err = fmt.Fprintf(f, TestSrcF, packet.Err, h, d.Opposite(), packet.Data)
|
_, err = fmt.Fprintf(f, TestSrcF, packet.Err, h, d.Opposite(), packet.Data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
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{
|
var StatusResponse = server.StatusResponse{
|
||||||
Version: struct {
|
Version: server.StatusResponseVersion{
|
||||||
Name *text.Component `json:"name"`
|
|
||||||
Protocol int `json:"protocol"`
|
|
||||||
}{
|
|
||||||
Name: text.Pretty("STROM"),
|
Name: text.Pretty("STROM"),
|
||||||
Protocol: 772,
|
Protocol: 772,
|
||||||
},
|
},
|
||||||
Players: struct {
|
Players: server.StatusResponsePlayers{},
|
||||||
Max int `json:"max"`
|
Description: text.Pretty("Hunt the un-code-able packets"),
|
||||||
Online int `json:"online"`
|
|
||||||
Sample []struct {
|
|
||||||
Name *text.Component `json:"name"`
|
|
||||||
ID string `json:"id"`
|
|
||||||
} `json:"sample"`
|
|
||||||
}{},
|
|
||||||
Description: text.Pretty("Hunt the uncodeable packets"),
|
|
||||||
Favicon: "",
|
Favicon: "",
|
||||||
EnforcesSecureChat: false,
|
EnforcesSecureChat: false,
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
slog.SetLogLoggerLevel(slog.LevelDebug)
|
||||||
err := server.StartServerWithOnConn(":25565", func(serveeConn *proto.Conn) (err error) {
|
err := server.StartServerWithOnConn(":25565", func(serveeConn *proto.Conn) (err error) {
|
||||||
p := &Proxy{Conn: serveeConn, Client: nil}
|
p := &Proxy{Conn: serveeConn, Client: nil}
|
||||||
acc := api.NewOfflineAccount("sigma")
|
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 {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
c, err := modules.ConnectAndLogin("127.0.0.1:25566", acc)
|
c, err := client.ConnectAndLogin("127.0.0.1:25566", acc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -161,7 +153,6 @@ func main() {
|
|||||||
p.Client = pc
|
p.Client = pc
|
||||||
errChan := make(chan error)
|
errChan := make(chan error)
|
||||||
defer pc.Close()
|
defer pc.Close()
|
||||||
defer p.Close()
|
|
||||||
go func() {
|
go func() {
|
||||||
errChan <- pc.Start(pc)
|
errChan <- pc.Start(pc)
|
||||||
}()
|
}()
|
||||||
|
|||||||
Reference in New Issue
Block a user