mirror of
https://github.com/BeamMP/BeamMP-Server.git
synced 2026-07-13 18:24:16 +00:00
Compare commits
111 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e58a241b28 | |||
| bf4c2d120e | |||
| 8b88127e20 | |||
| 6e7b2e0525 | |||
| 1e6c2ea680 | |||
| 140b43a18c | |||
| b8211166ad | |||
| 8e1d235dee | |||
| dc61d4649c | |||
| 03ac847683 | |||
| 3dde6a76cb | |||
| 87a0d46b00 | |||
| 452a4c5e16 | |||
| adfda5a8cb | |||
| 14097b6c68 | |||
| 7a21751750 | |||
| e68582871d | |||
| 3df71e96c5 | |||
| 6a1baa249a | |||
| 56cd0eca11 | |||
| 04e058dc0d | |||
| f359c0cdca | |||
| 9a45efef57 | |||
| b06d2fe151 | |||
| 145b74aefc | |||
| 1515fc2675 | |||
| 0f802e4021 | |||
| 213c1c7b6b | |||
| 787f59ba46 | |||
| 72bec02e21 | |||
| 46e42b88da | |||
| 39028ba4d7 | |||
| 9cd4609cad | |||
| 3b61da9edd | |||
| 09c4bb8b33 | |||
| f0a5fa48b8 | |||
| cfea87251b | |||
| 04c1b76402 | |||
| e15833084a | |||
| 13207a8ddf | |||
| d5aef2525f | |||
| efbd2a4bb8 | |||
| 478bf48a5a | |||
| 1e7cccd9a9 | |||
| 5fdfc10f79 | |||
| 7eaa382f6c | |||
| b66251d375 | |||
| e6f316a6c2 | |||
| 49a8e84161 | |||
| 3376eb7482 | |||
| de398c0208 | |||
| cde157fdfe | |||
| 3b0da388fb | |||
| ad49713e13 | |||
| 191264e732 | |||
| 88181cf44c | |||
| 03ea9513b9 | |||
| 6ed714b863 | |||
| 669e061fdf | |||
| 9b78fc76db | |||
| dfcf820824 | |||
| 259f3de774 | |||
| d9e0761e07 | |||
| 67cec26979 | |||
| 260fd03a1f | |||
| 2323c07d8e | |||
| a61554187e | |||
| 6c2b131d72 | |||
| 5a42fe87fd | |||
| 4551a2da60 | |||
| 223c9a5064 | |||
| 5097244c76 | |||
| 4e985bc0e0 | |||
| 7d0941dee8 | |||
| 0e75a35c83 | |||
| 7598261aff | |||
| 8280b06253 | |||
| 81816da44d | |||
| 7c82f474bb | |||
| 4bf4727cc3 | |||
| 0335d22809 | |||
| 0f5d61c89b | |||
| 37d7a289eb | |||
| 596a7234ed | |||
| 8735824495 | |||
| 51c5ee0638 | |||
| 4f57680a67 | |||
| 1c21298351 | |||
| e781bbac8e | |||
| a0db8aa8be | |||
| f2b9384447 | |||
| b5c6f2c3c7 | |||
| 6dee028a88 | |||
| 4f52e30545 | |||
| 01fb538129 | |||
| a23b5a43c0 | |||
| 8ee6ba16f2 | |||
| 0b6ad43fbb | |||
| 5d8c9cd792 | |||
| c5ce152a30 | |||
| 6c60f220eb | |||
| ff5a5204c9 | |||
| ad85317f60 | |||
| efad9ec03e | |||
| 5011ae280c | |||
| ebc0dba4ef | |||
| ad15846625 | |||
| e1b9f2b969 | |||
| 3fedcf5bd5 | |||
| 190cc8f238 | |||
| 38aaf29fe8 |
@@ -0,0 +1,21 @@
|
||||
name: Rust
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master" ]
|
||||
pull_request:
|
||||
branches: [ "master" ]
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Build
|
||||
run: cargo build --verbose
|
||||
- name: Run tests
|
||||
run: cargo test --verbose
|
||||
+4
-104
@@ -1,104 +1,4 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Directory for instrumented libs generated by jscoverage/JSCover
|
||||
lib-cov
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage
|
||||
*.lcov
|
||||
|
||||
# nyc test coverage
|
||||
.nyc_output
|
||||
|
||||
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
|
||||
.grunt
|
||||
|
||||
# Bower dependency directory (https://bower.io/)
|
||||
bower_components
|
||||
|
||||
# node-waf configuration
|
||||
.lock-wscript
|
||||
|
||||
# Compiled binary addons (https://nodejs.org/api/addons.html)
|
||||
build/Release
|
||||
|
||||
# Dependency directories
|
||||
node_modules/
|
||||
jspm_packages/
|
||||
|
||||
# TypeScript v1 declaration files
|
||||
typings/
|
||||
|
||||
# TypeScript cache
|
||||
*.tsbuildinfo
|
||||
|
||||
# Optional npm cache directory
|
||||
.npm
|
||||
|
||||
# Optional eslint cache
|
||||
.eslintcache
|
||||
|
||||
# Microbundle cache
|
||||
.rpt2_cache/
|
||||
.rts2_cache_cjs/
|
||||
.rts2_cache_es/
|
||||
.rts2_cache_umd/
|
||||
|
||||
# Optional REPL history
|
||||
.node_repl_history
|
||||
|
||||
# Output of 'npm pack'
|
||||
*.tgz
|
||||
|
||||
# Yarn Integrity file
|
||||
.yarn-integrity
|
||||
|
||||
# dotenv environment variables file
|
||||
.env
|
||||
.env.test
|
||||
|
||||
# parcel-bundler cache (https://parceljs.org/)
|
||||
.cache
|
||||
|
||||
# Next.js build output
|
||||
.next
|
||||
|
||||
# Nuxt.js build / generate output
|
||||
.nuxt
|
||||
dist
|
||||
|
||||
# Gatsby files
|
||||
.cache/
|
||||
# Comment in the public line in if your project uses Gatsby and *not* Next.js
|
||||
# https://nextjs.org/blog/next-9-1#public-directory-support
|
||||
# public
|
||||
|
||||
# vuepress build output
|
||||
.vuepress/dist
|
||||
|
||||
# Serverless directories
|
||||
.serverless/
|
||||
|
||||
# FuseBox cache
|
||||
.fusebox/
|
||||
|
||||
# DynamoDB Local files
|
||||
.dynamodb/
|
||||
|
||||
# TernJS port file
|
||||
.tern-port
|
||||
/target
|
||||
/.idea
|
||||
ServerConfig.toml
|
||||
beammp_rust_server.iml
|
||||
@@ -0,0 +1,82 @@
|
||||
# BeamMP Protocol Documentation
|
||||
WIP of course, but hope it helps others
|
||||
|
||||
## TCP
|
||||
### Basic message format
|
||||
All messages are sent as strings (?).
|
||||
Every packet starts with a 4 byte header, denoting how many bytes the packet data is.
|
||||
This means that you first must read 4 bytes from your socket, to get the header data, and afterwards read the data ready for reading.
|
||||
|
||||
### Communication flow
|
||||
Upon client connection:
|
||||
1. Authentication
|
||||
2. Sync with client?
|
||||
|
||||
#### Authentication
|
||||
1. C->S - Client sends the server a single byte. The BeamMP source checks for 3 letters, but I only saw C
|
||||
2. C->S - Client sends a packet containing the client version
|
||||
3. S->C - Server sends the server a regular packet containing only 1 byte: `S` (the ascii character)
|
||||
4. C->S - Client sends the server its public key
|
||||
5. S->C - Server sends the client their assigned server ID
|
||||
|
||||
#### Syncing resources
|
||||
1. C->S - Client sends the server a packet with the code `SR`
|
||||
2. S->C - Server sends the client a packet containing a filelist containing the name and size of files to download, or "-" if it's empty
|
||||
|
||||
### Packets
|
||||
All packets start with a single character, denoted as "Packet Code" or simply "Code" down below.
|
||||
The data mentioned is merely example data, to show the data format. This includes the code!
|
||||
Example:
|
||||
| Code | Dir | Explanation | Data |
|
||||
| ---- | --- | ----------- | ---- |
|
||||
| `C` | C->S | Client version | VC2.0 |
|
||||
|
||||
#### Uncategorized
|
||||
| Code | Dir | Explanation | Data |
|
||||
| ---- | --- | ----------- | ---- |
|
||||
| `J` | S->C | Show a message in the top left on the clients screen | JWelcome Luuk! |
|
||||
|
||||
#### Authentication
|
||||
| Code | Dir | Explanation | Data |
|
||||
| ---- | --- | ----------- | ---- |
|
||||
| `C` | C->S | Client version | VC2.0 |
|
||||
| `S` | S->C | Confirmation? | None |
|
||||
| `D` | C->S | Start download phase? Seems unused from testing | None |
|
||||
| `P` | S->C | Send client their assigned ID | P123 |
|
||||
|
||||
#### Syncing resources
|
||||
| Code | Dir | Explanation | Data |
|
||||
| ---- | --- | ----------- | ---- |
|
||||
| `SR` | C->S | Client requests a list containing all mods, containing their name and file size | None |
|
||||
| `f` | C->S | Client requests file with name | fcool_mod.zip |
|
||||
| `-` | S->C | Technically not a packet, see [Syncing Resources](https://github.com/Lucky4Luuk/beammp_rust_server/blob/master/BEAMMP_PROTOCOL_DOCS.md#syncing-resources), step 2. | * |
|
||||
|
||||
#### Syncing client state
|
||||
| Code | Dir | Explanation | Data |
|
||||
| ---- | --- | ----------- | ---- |
|
||||
| `H` | C->S | Client requests a full sync with the server state | None |
|
||||
|
||||
### Vehicle packets
|
||||
| Code | Dir | Explanation | Data |
|
||||
| ---- | --- | ----------- | ---- |
|
||||
| `Os` | C->S | Client informs server they are spawning a car | Os:C_ID:{car_json} |
|
||||
| `Os` | S->C | Server sends this packet to all clients, informing them a client has spawned a car | Os:C_ROLES:C_NAME:C_ID-CAR_ID:CAR_JSON |
|
||||
| `Or` | C->S | Client informs server they are respawning their car | Or:C_ID-CAR_ID:{respawn_json} |
|
||||
| `Or` | S->C | Server informs all other clients that a client is respawning their car | Or:C_ID-CAR_ID:{respawn_json} |
|
||||
| `Od` | C->S | Client informs server they are deleting their car | Od:C_ID-CAR_ID |
|
||||
| `Od` | S->C | Server informs all other clients that a client is deleting their car | Od:C_ID-CAR_ID |
|
||||
| `Oc` | C->S | Client informs server they are editing their car | Oc:?... |
|
||||
| `Oc` | S->C | Server informs all other clients that a client has edited their car | Oc:?... |
|
||||
|
||||
## UDP
|
||||
### Packets
|
||||
#### Uncategorized
|
||||
| Code | Dir | Explanation | Data |
|
||||
| ---- | --- | ----------- | ---- |
|
||||
| `p` | C->S | Ping! | None |
|
||||
| `p` | S->C | Pong! | None |
|
||||
|
||||
#### Vehicle related
|
||||
| Code | Dir | Explanation | Data |
|
||||
| ---- | --- | ----------- | ---- |
|
||||
| `Zp` | C->S | Positional packet | Zp:C_ID-CAR_ID:{transform_json} |
|
||||
Generated
+1801
File diff suppressed because it is too large
Load Diff
+36
@@ -0,0 +1,36 @@
|
||||
[package]
|
||||
name = "beammp_rust_server"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
log = "0.4"
|
||||
pretty_env_logger = "0.4.0"
|
||||
|
||||
argh = "0.1.12"
|
||||
|
||||
lazy_static = "1"
|
||||
|
||||
anyhow = "1.0.66"
|
||||
glam = "0.24.2"
|
||||
num_enum = "0.5.7"
|
||||
|
||||
async-trait = "0.1.58"
|
||||
tokio = { version = "1", features = ["macros", "rt", "rt-multi-thread", "net", "io-util", "sync"] }
|
||||
futures = "0.3.29"
|
||||
|
||||
reqwest = { version = "0.11", default-features = false, features = ["json", "rustls-tls"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde-aux = "4.2.0"
|
||||
serde_json = "*"
|
||||
|
||||
toml = "0.5"
|
||||
flate2 = "1.0"
|
||||
|
||||
mlua = { version = "0.9.1", features = ["lua54", "vendored", "send"] }
|
||||
|
||||
ratatui = "0.24.0"
|
||||
crossterm = "0.27.0"
|
||||
uuid = "1.6.1"
|
||||
@@ -0,0 +1,37 @@
|
||||
# This is the BeamMP-Server config file.
|
||||
# Help & Documentation: `https://wiki.beammp.com/en/home/server-maintenance`
|
||||
# IMPORTANT: Fill in the AuthKey with the key you got from `https://beammp.com/k/dashboard` on the left under "Keys"
|
||||
|
||||
[General]
|
||||
Name = "bepis big gaming"
|
||||
Port = 30814
|
||||
# AuthKey has to be filled out in order to run the server
|
||||
AuthKey = "test"
|
||||
# Whether to log chat messages in the console / log
|
||||
LogChat = true
|
||||
Debug = false
|
||||
Private = true
|
||||
MaxCars = 20
|
||||
MaxPlayers = 800000
|
||||
Map = "/levels/west_coast_usa/info.json"
|
||||
Description = "BeamMP Default Description"
|
||||
ResourceFolder = "Resources"
|
||||
|
||||
[Misc]
|
||||
# Hides the periodic update message which notifies you of a new server version. You should really keep this on and always update as soon as possible. For more information visit https://wiki.beammp.com/en/home/server-maintenance#updating-the-server. An update message will always appear at startup regardless.
|
||||
ImScaredOfUpdates = false
|
||||
# If SendErrors is `true`, the server will send helpful info about crashes and other issues back to the BeamMP developers. This info may include your config, who is on your server at the time of the error, and similar general information. This kind of data is vital in helping us diagnose and fix issues faster. This has no impact on server performance. You can opt-out of this system by setting this to `false`
|
||||
SendErrorsShowMessage = true
|
||||
# You can turn on/off the SendErrors message you get on startup here
|
||||
SendErrors = true
|
||||
|
||||
[HTTP]
|
||||
# Which IP to listen on. Pick 0.0.0.0 for a public-facing server with no specific IP, and 127.0.0.1 or 'localhost' for a local server.
|
||||
HTTPServerIP = "127.0.0.1"
|
||||
SSLKeyPath = "./.ssl/HttpServer/key.pem"
|
||||
SSLCertPath = "./.ssl/HttpServer/cert.pem"
|
||||
HTTPServerPort = 8080
|
||||
# Recommended to have enabled for servers which face the internet. With SSL the server will serve https and requires valid key and cert files
|
||||
UseSSL = false
|
||||
# Enables the internal HTTP server
|
||||
HTTPServerEnabled = false
|
||||
+661
@@ -0,0 +1,661 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero 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.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
BeamMP Server implemented in Rust
|
||||
Copyright (C) 2023 - Luuk van Oijen
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
@@ -1 +1,5 @@
|
||||
# BeamNG-MP-Server
|
||||
# BeamMP Server
|
||||
A BeamMP server implementation in Rust, meant to (hopefully) replace the official server implementation one day.
|
||||
|
||||
## Features
|
||||
TODO
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,61 @@
|
||||
print("test from lua")
|
||||
print("Player count: " .. MP.GetPlayerCount())
|
||||
|
||||
function onPluginLoaded()
|
||||
print("HI!")
|
||||
end
|
||||
|
||||
function onShutdown()
|
||||
print("BYE!")
|
||||
end
|
||||
|
||||
function onPlayerAuthenticated(joined_name, role, is_guest, identifiers)
|
||||
print("hi welcome mista " .. joined_name)
|
||||
print("u a guest? " .. tostring(is_guest))
|
||||
|
||||
print("current players:")
|
||||
for id, name in pairs(MP.GetPlayers()) do
|
||||
print("- [" .. id .. "]" .. name)
|
||||
end
|
||||
print("yipee")
|
||||
|
||||
print("Player count: " .. MP.GetPlayerCount())
|
||||
|
||||
for key, value in pairs(identifiers) do
|
||||
print(key .. ": " .. value)
|
||||
end
|
||||
|
||||
-- print("now trying with getting it ourself")
|
||||
-- for key, value in pairs(MP.GetPlayerIdentifiers(pid)) do
|
||||
-- print(key .. ": " .. value)
|
||||
-- end
|
||||
|
||||
return 0 -- 0 = do not cancel
|
||||
end
|
||||
|
||||
function onPlayerDisconnect(pid, name, identifiers)
|
||||
-- Player is already gone here, so for now, player data is no longer
|
||||
-- requestable for player with the id `pid`
|
||||
print("Player " .. name .. " (" .. pid .. ") has left!")
|
||||
end
|
||||
|
||||
function onChatMessage(pid, name, message)
|
||||
MP.SendChatMessage(-1, "i hate this " .. name .. " guy!")
|
||||
MP.SendChatMessage(pid, "hiii babe i didnt mean it :3")
|
||||
print("" .. name .. " (" .. pid .. "): " .. message)
|
||||
|
||||
print("identifiers:")
|
||||
for key, value in pairs(MP.GetPlayerIdentifiers(pid)) do
|
||||
print(key .. ": " .. value)
|
||||
end
|
||||
|
||||
print("unknown identifiers (nil): " .. tostring(MP.GetPlayerIdentifiers(100)))
|
||||
|
||||
return message .. " (edited by lua!!!)"
|
||||
end
|
||||
|
||||
MP.RegisterEventHandler("onInit", "onPluginLoaded")
|
||||
MP.RegisterEventHandler("onShutdown", "onShutdown")
|
||||
MP.RegisterEventHandler("onPlayerAuth", "onPlayerAuthenticated")
|
||||
MP.RegisterEventHandler("onPlayerDisconnect", "onPlayerDisconnect")
|
||||
MP.RegisterEventHandler("onChatMessage", "onChatMessage")
|
||||
@@ -1,345 +0,0 @@
|
||||
// Server Settings!
|
||||
var map = "";
|
||||
let _VERSION = "0.0.3"
|
||||
let UDPExpireTime = 30// In Seconds
|
||||
|
||||
const net = require('net');
|
||||
const uuidv4 = require('uuid/v4');
|
||||
const args = require('minimist')(process.argv.slice(2));
|
||||
const chalk = require("chalk")
|
||||
|
||||
//console.log(args.port)
|
||||
if (args.port) {
|
||||
var tcpport = args.port;
|
||||
} else {
|
||||
var tcpport = 30813;
|
||||
}
|
||||
|
||||
var udpport = tcpport + 1;
|
||||
var wsport = tcpport + 2;
|
||||
const host = '0.0.0.0';
|
||||
|
||||
//==========================================================
|
||||
// WebSocket Server
|
||||
//==========================================================
|
||||
|
||||
const WebSocket = require('ws');
|
||||
|
||||
const wss = new WebSocket.Server({ port: wsport });
|
||||
|
||||
wss.on('connection', function connection(ws) {
|
||||
ws.on('message', function incoming(message) {
|
||||
console.log('[WS] received: %s', message);
|
||||
wss.clients.forEach(function each(client) {
|
||||
if (client.readyState === WebSocket.OPEN) {
|
||||
client.send(message);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
ws.send('Welcome!');
|
||||
});
|
||||
console.log(chalk.cyan('[WS]')+' Server listening on 0.0.0.0:' + wsport);
|
||||
|
||||
//==========================================================
|
||||
// TCP Server
|
||||
//==========================================================
|
||||
|
||||
const TCPserver = net.createServer();
|
||||
TCPserver.listen(tcpport, () => {
|
||||
console.log(chalk.green('[TCP]')+' Server listening on 0.0.0.0:' + tcpport);
|
||||
});
|
||||
|
||||
let sockets = [];
|
||||
let players = [];
|
||||
let names = [];
|
||||
let vehicles = [];
|
||||
|
||||
TCPserver.on('connection', function(sock) {
|
||||
console.log(chalk.green('[TCP]')+' CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort);
|
||||
sockets.push(sock);
|
||||
|
||||
var player = {};
|
||||
player.remoteAddress = sock.remoteAddress;
|
||||
player.remotePort = sock.remotePort;
|
||||
player.nickname = "New User, Loading...";
|
||||
player.id = uuidv4();
|
||||
player.currentVehID = 0;
|
||||
players.push(player);
|
||||
|
||||
sock.write('HOLA'+player.id+'\n');
|
||||
if (map == "") {
|
||||
sock.write("MAPS\n");
|
||||
} else {
|
||||
sock.write("MAPC"+map+'\n')
|
||||
}
|
||||
sock.write("VCHK"+_VERSION+'\n')
|
||||
|
||||
sock.on('data', function(data) {
|
||||
// Write the data back to all the connected, the client will receive it as data from the server
|
||||
var str = data.toString();
|
||||
data = str.trim(); //replace(/\r?\n|\r/g, "");
|
||||
var code = data.substring(0, 4);
|
||||
var message = data.substr(4);
|
||||
|
||||
if (code != "PING") {
|
||||
//console.log(code)
|
||||
}
|
||||
//if (data.length > 4) {
|
||||
//console.log(data.length)
|
||||
//}
|
||||
|
||||
switch (code) {
|
||||
case "PING":
|
||||
//console.log("Ping Received")
|
||||
sock.write('PONG\n');
|
||||
break;
|
||||
case "CHAT":
|
||||
sockets.forEach(function(socket, index, array) { // Send update to all clients
|
||||
socket.write(data+'\n');
|
||||
});
|
||||
break;
|
||||
case "MAPS":
|
||||
map = message;
|
||||
console.log("Setting map to: "+map);
|
||||
sock.write("MAPC"+map+'\n');
|
||||
break;
|
||||
case "USER":
|
||||
players.forEach(function(player, index, array) {
|
||||
if (player.remoteAddress == sock.remoteAddress && player.remotePort == sock.remotePort) {
|
||||
console.log("Player Found ("+player.id+"), setting nickname("+data.substr(4)+")");
|
||||
player.nickname = ""+data.substr(4)+"";
|
||||
sockets.forEach(function(socket, index, array) { // Send update to all clients
|
||||
socket.write('PLST'+JSON.stringify(players)+'\n');
|
||||
socket.write('SMSG'+data.substr(4)+' Just Joined the Session.\n');
|
||||
});
|
||||
}
|
||||
});
|
||||
break;
|
||||
case "QUIT":
|
||||
case "2001":
|
||||
let index = sockets.findIndex(function(o) {
|
||||
return o.remoteAddress === sock.remoteAddress && o.remotePort === sock.remotePort;
|
||||
})
|
||||
if (index !== -1) sockets.splice(index, 1);
|
||||
console.log('CLOSED: ' + sock.remoteAddress + ' ' + sock.remotePort);
|
||||
break;
|
||||
case "U-VI":
|
||||
case "U-VE":
|
||||
case "U-VN":
|
||||
case "U-VP":
|
||||
case "U-VL":
|
||||
case "U-VR":
|
||||
case "U-VV":
|
||||
//console.log(data)
|
||||
//players.forEach(function(player, index, array) {
|
||||
//if (player.remoteAddress != sock.remoteAddress) {
|
||||
//console.log(player.remoteAddress+' != '+sock.remoteAddress+' Is not the same so we should send?')
|
||||
//console.log("Got Update to send!")
|
||||
sockets.forEach(function(socket, index, array) { // Send update to all clients
|
||||
//console.log(socket.remotePort+' != '+sock.remotePort+' Is not the same so we should send?')
|
||||
if ((sock.remoteAddress != socket.remoteAddress && sock.remotePort != socket.remotePort) || (sock.remoteAddress == socket.remoteAddress && sock.remotePort != socket.remotePort)) {
|
||||
socket.write(data+'\n');
|
||||
}
|
||||
});
|
||||
//}
|
||||
//});
|
||||
break;
|
||||
case "U-VC":
|
||||
sockets.forEach(function(socket, index, array) { // Send update to all clients
|
||||
socket.write(data+'\n');
|
||||
});
|
||||
break;
|
||||
case "U-NV":
|
||||
console.log(message)
|
||||
var vid = uuidv4();
|
||||
|
||||
break;
|
||||
case "C-VS": // Client has changed vehicle. lets update our records.
|
||||
console.log(message)
|
||||
players.forEach(function(player, index, array) {
|
||||
if (player.currentVehID != message && player.remoteAddress == sock.remoteAddress && player.remotePort == sock.remotePort) {
|
||||
console.log(chalk.green('[TCP]')+" Player Found ("+player.id+"), updating current vehile("+message+")");
|
||||
player.currentVehID = message;
|
||||
}
|
||||
});
|
||||
break;
|
||||
default:
|
||||
console.log(chalk.green('[TCP]')+' Unknown / unhandled data from:' + sock.remoteAddress);
|
||||
console.log(chalk.green('[TCP]')+' Data -> ' + data);
|
||||
sockets.forEach(function(socket, index, array) { // Send update to all clients
|
||||
//if ((sock.remoteAddress != socket.remoteAddress && sock.remotePort != socket.remotePort) || (sock.remoteAddress == socket.remoteAddress && sock.remotePort != socket.remotePort)) {
|
||||
socket.write(data+'\n');
|
||||
//}
|
||||
});
|
||||
break;
|
||||
}
|
||||
sockets.forEach(function(sock, index, array) {
|
||||
//sock.write(sock.remoteAddress + ':' + sock.remotePort + " said " + data + '\n');
|
||||
});
|
||||
});
|
||||
|
||||
// Add a 'close' event handler to this instance of socket
|
||||
sock.on('close', function(data) {
|
||||
var index = players.findIndex(function(o) {
|
||||
return o.remoteAddress === sock.remoteAddress && o.remotePort === sock.remotePort;
|
||||
})
|
||||
if (index !== -1) sockets.splice(index, 1);
|
||||
index = sockets.findIndex(function(o) {
|
||||
return o.remoteAddress === sock.remoteAddress && o.remotePort === sock.remotePort;
|
||||
})
|
||||
if (index !== -1) sockets.splice(index, 1);
|
||||
console.log('CLOSED: ' + sock.remoteAddress + ' ' + sock.remotePort);
|
||||
players = removePlayer(players, sock.remoteAddress);
|
||||
console.log("Player list now holds: "+JSON.stringify(players));
|
||||
sockets.forEach(function(socket, index, array) { // Send update to all clients
|
||||
socket.write('PLST'+JSON.stringify(players)+'\n');
|
||||
});
|
||||
});
|
||||
|
||||
sock.on('error', (err) => {
|
||||
// handle errors here
|
||||
if (err.code == "ECONNRESET") {
|
||||
console.error(chalk.red("ERROR ")+"Connection Reset for player: ");
|
||||
players.forEach(function(player, index, array) {
|
||||
if (player.remoteAddress == sock.remoteAddress && player.remotePort == sock.remotePort) {
|
||||
console.error(+player.nickname+" ("+player.id+")");
|
||||
console.error(chalk.red("ERROR ")+"End Error.");
|
||||
}
|
||||
});
|
||||
} else {
|
||||
console.error("Sock Error");
|
||||
console.error(err);
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
TCPserver.on('error', (err) => {
|
||||
// handle errors here
|
||||
console.error("TCPserver Error");
|
||||
console.error(err);
|
||||
throw err;
|
||||
});
|
||||
|
||||
function removePlayer(array, ip) {
|
||||
return array.filter(player => player.remoteAddress != ip);
|
||||
}
|
||||
|
||||
//==========================================================
|
||||
// UDP Server
|
||||
//==========================================================
|
||||
|
||||
var clients = {};
|
||||
var intervalTime = UDPExpireTime*2*1000;
|
||||
|
||||
setInterval(function() {
|
||||
console.log(clients);
|
||||
for (var client in clients) {
|
||||
var lastupdate = clients[client];
|
||||
var millis = Date.now() - lastupdate;
|
||||
var t = Math.floor(millis/1000)
|
||||
if (t > UDPExpireTime) {
|
||||
console.warn("Found Old Client: "+client)
|
||||
delete clients[client];
|
||||
}
|
||||
}
|
||||
}, intervalTime);
|
||||
|
||||
function updateClient (rinfo) {
|
||||
for (var client in clients) {
|
||||
client = JSON.parse(client);
|
||||
var address = client[0];
|
||||
var port = client[1];
|
||||
if (port == rinfo.port && address == rinfo.address) {
|
||||
client
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var dgram = require('dgram');
|
||||
var UDPserver = dgram.createSocket('udp4');
|
||||
|
||||
function UDPsend(message, info) {
|
||||
UDPserver.send(message, 0, message.length, info.port, info.address, function(error){
|
||||
if (error) {
|
||||
console.log("ERROR");
|
||||
console.log(error);
|
||||
client.close();
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
UDPserver.on('listening', function() {
|
||||
var address = UDPserver.address();
|
||||
console.log(chalk.rgb(123, 45, 67)('[UDP]')+' Server listening on ' + address.address + ':' + address.port);
|
||||
});
|
||||
|
||||
UDPserver.on('message',function(msg,rinfo){
|
||||
clients[JSON.stringify([rinfo.address, rinfo.port])] = Date.now();
|
||||
//sending msg
|
||||
var str = msg.toString();
|
||||
data = str.trim(); //replace(/\r?\n|\r/g, "");
|
||||
var code = data.substring(0, 4);
|
||||
//if (code != "PING") {
|
||||
//console.log(msg.toString());
|
||||
//}
|
||||
switch (code) {
|
||||
case "PING":
|
||||
UDPsend("PONG", rinfo)
|
||||
break;
|
||||
case "U-VC":
|
||||
for (var client in clients) {
|
||||
client = JSON.parse(client);
|
||||
var port = client[1];
|
||||
var address = client[0];
|
||||
UDPserver.send(msg, 0, msg.length, port, address, function(error){
|
||||
if (error) {
|
||||
console.log("ERROR");
|
||||
console.log(error);
|
||||
client.close();
|
||||
};
|
||||
});
|
||||
}
|
||||
break;
|
||||
case "U-VR":
|
||||
case "U-VL":
|
||||
case "U-VP":
|
||||
case "U-VN":
|
||||
case "U-VE":
|
||||
case "U-VI":
|
||||
for (var client in clients) {
|
||||
client = JSON.parse(client);
|
||||
var port = client[1];
|
||||
var address = client[0];
|
||||
if (port != rinfo.port && address != rinfo.address) {
|
||||
UDPserver.send(msg, 0, msg.length, port, address, function(error){
|
||||
if (error) {
|
||||
console.log("ERROR");
|
||||
console.log(error);
|
||||
client.close();
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
break;
|
||||
default:
|
||||
// Unhandled data, this at the moment includes the extra packets of vehicles so it needs to be here until it is handled correctly
|
||||
for (var client in clients) {
|
||||
client = JSON.parse(client);
|
||||
var port = client[1];
|
||||
var address = client[0];
|
||||
UDPserver.send(msg, 0, msg.length, port, address, function(error){
|
||||
if (error) {
|
||||
console.log("ERROR");
|
||||
console.log(error);
|
||||
client.close();
|
||||
};
|
||||
});
|
||||
}
|
||||
//console.log(chalk.rgb(123, 45, 67)('[UDP]')+' Data received from client : ' + msg.toString());
|
||||
//console.log(chalk.rgb(123, 45, 67)('[UDP]')+' Received %d bytes from %s:%d\n',msg.length, rinfo.address, rinfo.port);
|
||||
}
|
||||
});
|
||||
|
||||
UDPserver.bind(Number(udpport));
|
||||
Generated
-1268
File diff suppressed because it is too large
Load Diff
@@ -1,20 +0,0 @@
|
||||
{
|
||||
"name": "beamng.drive-mp-server",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "main.js",
|
||||
"scripts": {
|
||||
"start": "electron ."
|
||||
},
|
||||
"author": "Mitch Durso",
|
||||
"license": "ISC",
|
||||
"devDependencies": {
|
||||
"electron": "^6.0.7"
|
||||
},
|
||||
"dependencies": {
|
||||
"chalk": "^3.0.0",
|
||||
"minimist": "^1.2.0",
|
||||
"uuid": "^3.3.3",
|
||||
"ws": "^7.2.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
use serde::Deserialize;
|
||||
use uuid::Uuid;
|
||||
use crate::fs_util;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct Config {
|
||||
#[serde(skip)] // Skipping uses Default::default, which makes a new vector for us :)
|
||||
pub mods: Vec<(String, usize)>,
|
||||
|
||||
#[serde(rename = "General")]
|
||||
pub general: GeneralSettings,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct GeneralSettings {
|
||||
#[serde(rename = "Port")]
|
||||
pub port: Option<u16>,
|
||||
|
||||
#[serde(rename = "Name")]
|
||||
pub name: String,
|
||||
|
||||
#[serde(rename = "Description")]
|
||||
pub description: String,
|
||||
|
||||
#[serde(rename = "AuthKey")]
|
||||
pub auth_key: Option<String>,
|
||||
|
||||
#[serde(rename = "MaxCars")]
|
||||
pub max_cars: Option<u8>,
|
||||
|
||||
#[serde(rename = "MaxPlayers")]
|
||||
pub max_players: usize,
|
||||
|
||||
#[serde(rename = "Private")]
|
||||
pub private: bool,
|
||||
|
||||
#[serde(rename = "Map")]
|
||||
pub map: String,
|
||||
|
||||
#[serde(rename = "ResourceFolder")]
|
||||
pub resource_folder: String,
|
||||
|
||||
#[serde(rename = "Debug")]
|
||||
pub debug: bool,
|
||||
|
||||
// Options below are not yet supported
|
||||
#[serde(rename = "LogChat")]
|
||||
pub log_chat: bool,
|
||||
}
|
||||
|
||||
impl GeneralSettings {
|
||||
pub fn is_auth_key_valid(&self) -> bool {
|
||||
if let Some(auth_key) = &self.auth_key {
|
||||
Uuid::parse_str(auth_key.as_str()).is_ok()
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the client resource path, and ensures it exists.
|
||||
/// Default is Resources/Client.
|
||||
pub fn get_client_resource_folder(&self) -> anyhow::Result<String> {
|
||||
let res_client_path = Path::new(self.resource_folder.as_str()).join("Client");
|
||||
fs_util::ensure_path_exists(&res_client_path)?;
|
||||
Ok(fs_util::path_to_string(res_client_path))
|
||||
}
|
||||
|
||||
/// Returns the server resource path, and ensures it exists.
|
||||
/// Default is Resources/Server.
|
||||
pub fn get_server_resource_folder(&self) -> anyhow::Result<String> {
|
||||
let res_server_path = Path::new(self.resource_folder.as_str()).join("Server");
|
||||
fs_util::ensure_path_exists(&res_server_path)?;
|
||||
Ok(fs_util::path_to_string(res_server_path))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Ensures the given path exists by creating it if it doesn't.
|
||||
pub fn ensure_path_exists(path: &PathBuf) -> anyhow::Result<()> {
|
||||
if !path.exists() {
|
||||
debug!("Path {:?} doesn't exist, creating it", path);
|
||||
std::fs::create_dir_all(path)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Joins a parent folder and a sub-path, resolving the subpath beforehand to ensure that
|
||||
/// the resulting path is still within the parent folder, regardless of ".." in the sub-path.
|
||||
pub fn join_path_secure(parent: &Path, sub: &Path) -> anyhow::Result<PathBuf> {
|
||||
Ok(parent.join(sub.file_name().unwrap_or("".as_ref())))
|
||||
}
|
||||
|
||||
/// Converts a PathBuf into a String in a lossy way. This is generally the way we want to do it
|
||||
/// in the server.
|
||||
pub fn path_to_string(path: PathBuf) -> String {
|
||||
path.into_os_string().to_string_lossy().to_string()
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
use serde::Serialize;
|
||||
use tokio::sync::mpsc::Receiver;
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct HeartbeatInfo {
|
||||
uuid: String,
|
||||
players: usize,
|
||||
maxplayers: usize,
|
||||
port: u16,
|
||||
map: String,
|
||||
private: String, // Needs to be either "true" or "false"
|
||||
version: String,
|
||||
clientversion: String,
|
||||
name: String,
|
||||
modlist: String,
|
||||
modstotalsize: usize,
|
||||
modstotal: usize,
|
||||
playerslist: String,
|
||||
desc: String,
|
||||
}
|
||||
|
||||
pub async fn backend_heartbeat(config: std::sync::Arc<crate::config::Config>, mut hb_rx: Receiver<crate::server::ServerStatus>) {
|
||||
if !config.general.is_auth_key_valid() {
|
||||
if config.general.private {
|
||||
warn!("AuthKey has invalid format. This is not an error, since your server is private.");
|
||||
} else {
|
||||
error!("AuthKey has invalid format. The server will not appear on the server list.");
|
||||
}
|
||||
// FIXME: The heartbeat should be started if the config is ever changed/reloaded.
|
||||
return;
|
||||
}
|
||||
let mut info = HeartbeatInfo {
|
||||
uuid: config.general.auth_key.clone().unwrap_or(String::from("Unknown name!")),
|
||||
players: 0,
|
||||
maxplayers: config.general.max_players,
|
||||
port: config.general.port.unwrap_or(30814),
|
||||
map: config.general.map.clone(),
|
||||
private: if config.general.private { String::from("true") } else { String::from("false") },
|
||||
version: String::from("3.3.0"), // TODO: Don't hardcode this
|
||||
clientversion: String::from("2.0"), // TODO: What? I think for now I can fill in 2.0
|
||||
name: config.general.name.clone(),
|
||||
modlist: String::from("-"), // TODO: Implement this
|
||||
modstotalsize: 0, // TODO: Implement this
|
||||
modstotal: 0, // TODO: Implement this
|
||||
playerslist: String::new(),
|
||||
desc: config.general.description.clone(),
|
||||
};
|
||||
|
||||
let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(30));
|
||||
loop {
|
||||
interval.tick().await;
|
||||
|
||||
tokio::select! {
|
||||
_ = heartbeat_post(&info) => {}
|
||||
status = hb_rx.recv() => {
|
||||
if let Some(status) = status {
|
||||
trace!("status update: {:?}", status);
|
||||
info.players = status.player_count;
|
||||
info.playerslist = status.player_list.iter().map(|(_id, name)| format!("{};", name)).collect();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn heartbeat_post(heartbeat_info: &HeartbeatInfo) {
|
||||
match reqwest::Client::builder()
|
||||
.local_address("0.0.0.0".parse::<std::net::IpAddr>().unwrap())
|
||||
.build().unwrap()
|
||||
.post("https://backend.beammp.com/heartbeat")
|
||||
.form(heartbeat_info)
|
||||
.send()
|
||||
.await
|
||||
{
|
||||
Ok(resp) => {
|
||||
trace!("heartbeat response:\n{:?}", resp.text().await);
|
||||
},
|
||||
Err(e) => error!("Heartbeat error occured: {e}"),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
use log::{Record, Level, Metadata, SetLoggerError, LevelFilter};
|
||||
use std::sync::Mutex;
|
||||
|
||||
lazy_static! {
|
||||
static ref LOG_BUFFER: Mutex<Vec<(Level, String)>> = Mutex::new(Vec::new());
|
||||
}
|
||||
|
||||
struct BufferedLogger;
|
||||
|
||||
impl log::Log for BufferedLogger {
|
||||
fn enabled(&self, metadata: &Metadata) -> bool {
|
||||
let mut enabled = true;
|
||||
if metadata.level() != Level::Error {
|
||||
if metadata.target().starts_with("rustls") {
|
||||
enabled = false;
|
||||
}
|
||||
}
|
||||
enabled
|
||||
}
|
||||
|
||||
fn log(&self, record: &Record) {
|
||||
if self.enabled(record.metadata()) {
|
||||
let msg = format!("{}", record.args());
|
||||
let mut lock = LOG_BUFFER.lock().expect("Logging lock poisoned!");
|
||||
lock.push((record.level(), msg));
|
||||
}
|
||||
}
|
||||
|
||||
fn flush(&self) {}
|
||||
}
|
||||
|
||||
static LOGGER: BufferedLogger = BufferedLogger;
|
||||
|
||||
pub fn init(filter: LevelFilter) -> Result<(), SetLoggerError> {
|
||||
log::set_logger(&LOGGER)
|
||||
.map(|()| log::set_max_level(filter))
|
||||
}
|
||||
|
||||
pub async fn drain_log_buffer() -> Vec<(Level, String)> {
|
||||
let mut lock = LOG_BUFFER.lock().expect("Logging lock poisoned!");
|
||||
let v = lock.drain(..).collect();
|
||||
drop(lock);
|
||||
v
|
||||
}
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
#[macro_use] extern crate log;
|
||||
#[macro_use] extern crate async_trait;
|
||||
#[macro_use] extern crate lazy_static;
|
||||
|
||||
use std::path::Path;
|
||||
use argh::FromArgs;
|
||||
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
mod logger;
|
||||
mod tui;
|
||||
mod server;
|
||||
mod config;
|
||||
mod heartbeat;
|
||||
mod fs_util;
|
||||
|
||||
#[derive(FromArgs)]
|
||||
/// BeamMP Server v3.3.0
|
||||
struct Args {
|
||||
/// disables the TUI and shows a simple console log instead
|
||||
#[argh(switch)]
|
||||
disable_tui: bool,
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let args: Args = argh::from_env();
|
||||
|
||||
let mut user_config: config::Config = toml::from_str(
|
||||
&std::fs::read_to_string("ServerConfig.toml")
|
||||
.map_err(|_| error!("Failed to read config file!"))
|
||||
.expect("Failed to read config file!")
|
||||
)
|
||||
.map_err(|_| eprintln!("Failed to parse config file!"))
|
||||
.expect("Failed to parse config file!");
|
||||
|
||||
let level_filter = if user_config.general.debug { log::LevelFilter::max() } else { log::LevelFilter::Info };
|
||||
if !args.disable_tui {
|
||||
logger::init(level_filter).expect("Failed to enable logger!");
|
||||
} else {
|
||||
pretty_env_logger::formatted_timed_builder()
|
||||
.filter_level(level_filter)
|
||||
.filter_module("rustls", log::LevelFilter::Error)
|
||||
.init();
|
||||
}
|
||||
|
||||
let client_resources = user_config.general
|
||||
.get_client_resource_folder()
|
||||
.expect("Failed to create the client resource folder");
|
||||
|
||||
for entry in std::fs::read_dir(client_resources).expect("Failed to read client resource folder!") {
|
||||
if let Ok(entry) = entry {
|
||||
if entry.path().is_file() {
|
||||
if let Ok(metadata) = entry.metadata() {
|
||||
if let Some(filename) = entry.path().file_name().map(|s| s.to_string_lossy()) {
|
||||
let mut name = filename.to_string();
|
||||
if !name.starts_with("/") {
|
||||
name = format!("/{name}");
|
||||
}
|
||||
user_config.mods.push((name, metadata.len() as usize));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
debug!("Mods: {:?}", user_config.mods);
|
||||
|
||||
let user_config = Arc::new(user_config);
|
||||
|
||||
let (cmd_tx, cmd_rx) = mpsc::channel(100);
|
||||
let (status_tx, status_rx) = mpsc::channel(100);
|
||||
|
||||
if !args.disable_tui {
|
||||
tokio::spawn(tui::tui_main(user_config.clone(), cmd_tx, status_rx));
|
||||
}
|
||||
|
||||
server_main(user_config, cmd_rx, status_tx).await;
|
||||
}
|
||||
|
||||
async fn server_main(user_config: Arc<config::Config>, mut cmd_rx: mpsc::Receiver<Vec<String>>, status_tx: mpsc::Sender<server::ServerStatus>) {
|
||||
let (hb_tx, hb_rx) = mpsc::channel(100);
|
||||
|
||||
tokio::spawn(heartbeat::backend_heartbeat(user_config.clone(), hb_rx));
|
||||
|
||||
let mut server = server::Server::new(user_config)
|
||||
.await
|
||||
.map_err(|e| error!("{:?}", e))
|
||||
.expect("Failed to start server!");
|
||||
|
||||
let mut status = server.get_server_status();
|
||||
hb_tx.send(status.clone()).await;
|
||||
status_tx.send(status.clone()).await;
|
||||
'server: loop {
|
||||
// TODO: Error handling
|
||||
if server.clients.len() > 0 {
|
||||
tokio::select! {
|
||||
ret = server::read_tcp(&mut server.clients) => {
|
||||
match ret {
|
||||
Ok(ret) => if let Some((index, packet)) = ret {
|
||||
server.process_tcp(index, packet).await;
|
||||
},
|
||||
Err(e) => error!("Error: {e}"),
|
||||
}
|
||||
}
|
||||
ret = server::read_udp(&mut server.udp_socket) => {
|
||||
if let Some((addr, packet)) = ret {
|
||||
server.process_udp(addr, packet).await;
|
||||
}
|
||||
}
|
||||
_ = tokio::time::sleep(tokio::time::Duration::from_millis(50)) => {}
|
||||
}
|
||||
} else {
|
||||
// TODO: Scuffed?
|
||||
tokio::time::sleep(tokio::time::Duration::from_millis(150)).await;
|
||||
}
|
||||
|
||||
if let Err(e) = server.process().await {
|
||||
error!("{:?}", e);
|
||||
}
|
||||
|
||||
let new_status = server.get_server_status();
|
||||
|
||||
if status != new_status {
|
||||
status = new_status;
|
||||
hb_tx.send(status.clone()).await;
|
||||
status_tx.send(status.clone()).await;
|
||||
}
|
||||
|
||||
// Process commands
|
||||
match cmd_rx.try_recv() {
|
||||
Ok(cmd) => if cmd.len() > 0 {
|
||||
match cmd[0].as_str() {
|
||||
"exit" => {
|
||||
server.close().await;
|
||||
break 'server;
|
||||
},
|
||||
"players" => {
|
||||
let mut pl = "Players:\n".to_string();
|
||||
for (i, (id, player)) in status.player_list.iter().enumerate() {
|
||||
pl.push_str(&format!("\t[{: >2}] - {player}", id));
|
||||
if i + 1 < status.player_list.len() {
|
||||
pl.push('\n');
|
||||
}
|
||||
}
|
||||
info!("{}", pl);
|
||||
},
|
||||
"say" => {
|
||||
let msg = cmd[1..].iter().map(|s| s.as_str()).collect::<Vec<&str>>().join(" ");
|
||||
server.send_chat_message(&msg, None).await;
|
||||
},
|
||||
_ => info!("Unknown command!"),
|
||||
}
|
||||
} else {
|
||||
// what!
|
||||
},
|
||||
Err(mpsc::error::TryRecvError::Empty) => {},
|
||||
Err(e) => {
|
||||
error!("Error: {e}");
|
||||
break;
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
use serde::de::DeserializeOwned;
|
||||
use std::collections::HashMap;
|
||||
|
||||
static BACKEND_URL: &'static str = "backend.beammp.com";
|
||||
static AUTH_URL: &'static str = "auth.beammp.com";
|
||||
|
||||
pub async fn authentication_request<R: DeserializeOwned>(
|
||||
target: &str,
|
||||
map: HashMap<String, String>,
|
||||
) -> anyhow::Result<R> {
|
||||
let client = reqwest::Client::new();
|
||||
let resp = client
|
||||
.post(format!("https://{}/{}", AUTH_URL, target))
|
||||
.json(&map)
|
||||
.send()
|
||||
.await?;
|
||||
// panic!("json: {:?}", resp.text().await);
|
||||
Ok(resp.json().await?)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
use glam::*;
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
#[derive(Default, Clone, Debug)]
|
||||
pub struct Car {
|
||||
pub car_json: String,
|
||||
|
||||
pub pos: DVec3,
|
||||
pub rot: DQuat,
|
||||
pub vel: DVec3,
|
||||
pub rvel: DVec3,
|
||||
pub tim: f64,
|
||||
pub ping: f64,
|
||||
pub last_pos_update: Option<Instant>,
|
||||
}
|
||||
|
||||
impl Car {
|
||||
pub fn new(car_json: String) -> Self {
|
||||
Self {
|
||||
car_json: car_json,
|
||||
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn raw_position(&self) -> DVec3 {
|
||||
self.pos
|
||||
}
|
||||
|
||||
pub fn raw_rotation(&self) -> DQuat {
|
||||
self.rot
|
||||
}
|
||||
|
||||
pub fn position(&self) -> DVec3 {
|
||||
self.pos + self.vel * self.last_pos_update.map(|t| t.elapsed().as_secs_f64()).unwrap_or(0.0)
|
||||
}
|
||||
|
||||
pub fn rotation(&self) -> DQuat {
|
||||
let t = self.last_pos_update.map(|t| t.elapsed().as_secs_f64()).unwrap_or(0.0);
|
||||
self.rot + DQuat::from_euler(glam::EulerRot::YXZ, self.rvel.x * t, self.rvel.y * t, self.rvel.z * t)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,535 @@
|
||||
use std::collections::HashMap;
|
||||
use std::net::SocketAddr;
|
||||
use std::ops::DerefMut;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::{
|
||||
tcp::{OwnedReadHalf, OwnedWriteHalf},
|
||||
TcpStream,
|
||||
};
|
||||
use tokio::sync::mpsc::{Receiver, Sender};
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
use serde::Deserialize;
|
||||
use crate::fs_util;
|
||||
|
||||
use super::backend::*;
|
||||
use super::car::*;
|
||||
use super::packet::*;
|
||||
|
||||
lazy_static! {
|
||||
pub static ref TAKEN_PLAYER_IDS: Mutex<Vec<u8>> = Mutex::new(Vec::new());
|
||||
pub static ref CLIENT_MOD_PROGRESS: Mutex<HashMap<u8, isize>> = Mutex::new(HashMap::new());
|
||||
}
|
||||
|
||||
// TODO: Return a proper error?
|
||||
async fn claim_id() -> Result<u8, ()> {
|
||||
let mut lock = TAKEN_PLAYER_IDS.lock().await;
|
||||
for index in 0..=255 {
|
||||
if !lock.contains(&index) {
|
||||
lock.push(index);
|
||||
return Ok(index);
|
||||
}
|
||||
}
|
||||
// requires more then 255 players on the server to error
|
||||
Err(())
|
||||
}
|
||||
|
||||
async fn free_id(id: u8) {
|
||||
let mut lock = TAKEN_PLAYER_IDS.lock().await;
|
||||
*lock = lock.drain(..).filter(|i| *i != id).collect::<Vec<u8>>();
|
||||
}
|
||||
|
||||
#[derive(PartialEq)]
|
||||
pub enum ClientState {
|
||||
None,
|
||||
Connecting,
|
||||
SyncingResources,
|
||||
Syncing,
|
||||
Disconnect,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug, PartialEq, Clone)]
|
||||
pub struct UserData {
|
||||
pub uid: String,
|
||||
pub createdAt: String,
|
||||
pub guest: bool,
|
||||
pub roles: String,
|
||||
pub username: String,
|
||||
}
|
||||
|
||||
pub struct Client {
|
||||
pub id: u8,
|
||||
pub udp_addr: Option<SocketAddr>,
|
||||
|
||||
socket: OwnedReadHalf,
|
||||
write_half: Arc<Mutex<OwnedWriteHalf>>,
|
||||
write_runtime: JoinHandle<()>,
|
||||
write_runtime_sender: Sender<Packet>,
|
||||
|
||||
pub state: ClientState,
|
||||
pub info: Option<UserData>,
|
||||
pub cars: Vec<(u8, Car)>,
|
||||
}
|
||||
|
||||
impl Drop for Client {
|
||||
fn drop(&mut self) {
|
||||
tokio::spawn(free_id(self.id));
|
||||
self.write_runtime.abort();
|
||||
}
|
||||
}
|
||||
|
||||
impl Client {
|
||||
pub async fn new(socket: TcpStream) -> Self {
|
||||
let id = match claim_id().await {
|
||||
Ok(v) => v,
|
||||
Err(_) => panic!("CRITICAL: Saturated Player ID's"),
|
||||
};
|
||||
trace!("Client with ID #{} created!", id);
|
||||
|
||||
let (read_half, write_half) = socket.into_split();
|
||||
let (tx, mut rx): (Sender<Packet>, Receiver<Packet>) = tokio::sync::mpsc::channel(128);
|
||||
let write_half = Arc::new(Mutex::new(write_half));
|
||||
let write_half_ref = Arc::clone(&write_half);
|
||||
let handle: JoinHandle<()> = tokio::spawn(async move {
|
||||
loop {
|
||||
if let Some(packet) = rx.recv().await {
|
||||
// trace!("Runtime received packet...");
|
||||
let mut lock = write_half_ref.lock().await;
|
||||
// trace!("Runtime sending packet!");
|
||||
if let Err(e) = tcp_write(lock.deref_mut(), packet).await {
|
||||
error!("{:?}", e);
|
||||
};
|
||||
// trace!("Runtime sent packet!");
|
||||
drop(lock);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Self {
|
||||
id: id,
|
||||
udp_addr: None,
|
||||
|
||||
socket: read_half,
|
||||
write_half: write_half,
|
||||
write_runtime: handle,
|
||||
write_runtime_sender: tx,
|
||||
|
||||
state: ClientState::Connecting,
|
||||
info: None,
|
||||
cars: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn authenticate(&mut self, config: &super::Config) -> anyhow::Result<bool> {
|
||||
debug!("Authenticating client {}...", self.id);
|
||||
|
||||
// TODO: Check client version
|
||||
trace!("Client version packet");
|
||||
self.socket.readable().await?;
|
||||
let packet = self.read_packet_waiting().await?;
|
||||
debug!("{:?}", packet);
|
||||
|
||||
self.write_packet(Packet::Raw(RawPacket::from_code('S')))
|
||||
.await?;
|
||||
|
||||
self.socket.readable().await?;
|
||||
if let Some(packet) = self.read_packet_waiting().await? {
|
||||
debug!("packet: {:?}", packet);
|
||||
if packet.data.len() > 50 {
|
||||
self.kick("Player key too big!").await;
|
||||
return Err(ClientError::AuthenticateError.into());
|
||||
}
|
||||
let mut json = HashMap::new();
|
||||
let key = packet.data_as_string();
|
||||
debug!("[AUTH] key: {}", key);
|
||||
json.insert("key".to_string(), key);
|
||||
let user_data: UserData =
|
||||
authentication_request("pkToUser", json)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!("[AUTH] {:?}", e);
|
||||
e
|
||||
})?;
|
||||
debug!("user_data: {:?}", user_data);
|
||||
self.info = Some(user_data);
|
||||
|
||||
// self.write_packet(Packet::Raw(RawPacket::from_code('S')))
|
||||
// .await?;
|
||||
} else {
|
||||
self.kick(
|
||||
"Client never sent public key! If this error persists, try restarting your game.",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
self.write_packet(Packet::Raw(RawPacket::from_str(&format!("P{}", self.id))))
|
||||
.await?;
|
||||
|
||||
self.state = ClientState::SyncingResources;
|
||||
|
||||
debug!(
|
||||
"Authentication of client {} succesfully completed! Syncing now...",
|
||||
self.id
|
||||
);
|
||||
self.sync(config).await?;
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
// TODO: https://github.com/BeamMP/BeamMP-Server/blob/master/src/TNetwork.cpp#L619
|
||||
pub async fn sync(&mut self, config: &super::Config) -> anyhow::Result<()> {
|
||||
'syncing: while self.state == ClientState::SyncingResources {
|
||||
self.socket.readable().await?;
|
||||
if let Some(packet) = self.read_packet().await? {
|
||||
if (packet.data.len() == 4 && packet.data == [68, 111, 110, 101]) || packet.data.len() == 0 {
|
||||
{
|
||||
let mut lock = CLIENT_MOD_PROGRESS.lock().await;
|
||||
lock.insert(self.id, -1);
|
||||
}
|
||||
break 'syncing;
|
||||
}
|
||||
match packet.data[0] as char {
|
||||
'S' if packet.data.len() > 1 => match packet.data[1] as char {
|
||||
'R' => {
|
||||
let file_packet = if config.mods.len() == 0 {
|
||||
RawPacket::from_code('-')
|
||||
} else {
|
||||
let mut file_data = String::new();
|
||||
// TODO: Collapse these 2 loops into 1
|
||||
for (name, _size) in &config.mods {
|
||||
let mut mod_name = name.clone();
|
||||
if mod_name.starts_with("/") == false {
|
||||
mod_name = format!("/{mod_name}");
|
||||
}
|
||||
file_data.push_str(&format!("{mod_name};"));
|
||||
}
|
||||
for (_name, size) in &config.mods {
|
||||
file_data.push_str(&format!("{size};"));
|
||||
}
|
||||
RawPacket::from_str(&file_data)
|
||||
};
|
||||
// let file_packet = RawPacket::from_code('-');
|
||||
self.write_packet(Packet::Raw(file_packet))
|
||||
.await?;
|
||||
}
|
||||
_ => error!("Unknown packet! {:?}", packet),
|
||||
}
|
||||
'f' => {
|
||||
// Handle file download
|
||||
let mut mod_name = packet.data_as_string().clone();
|
||||
mod_name.remove(0); // Remove f
|
||||
debug!("Client is requesting file {}", mod_name);
|
||||
|
||||
let client_resources = config.general.get_client_resource_folder()?;
|
||||
let mod_path = fs_util::join_path_secure(Path::new(&client_resources), Path::new(&mod_name))?;
|
||||
|
||||
if !mod_path.exists() || !mod_path.is_file() {
|
||||
error!("Client requested mod which doesn't exist: {:?}. Disconnecting", mod_path);
|
||||
self.kick("Invalid mod request").await;
|
||||
return Ok(()) // client requested mod that doesnt exists within "Resources/Client/*"
|
||||
}
|
||||
|
||||
self.write_packet(Packet::Raw(RawPacket::from_str("AG"))).await?;
|
||||
|
||||
let mut mod_id = 0;
|
||||
for (i, (bmod_name, _bmod_size)) in config.mods.iter().enumerate() {
|
||||
if bmod_name == &mod_name {
|
||||
mod_id = i;
|
||||
}
|
||||
}
|
||||
|
||||
// Send the first half of the file over this socket and the other over the DSocket
|
||||
let file_data = std::fs::read(mod_path)?;
|
||||
{
|
||||
let mut lock = self.write_half.lock().await;
|
||||
lock.writable().await?;
|
||||
trace!("Sending packets!");
|
||||
if let Err(e) = lock.write(&file_data[..(file_data.len()/2)]).await {
|
||||
error!("{:?}", e);
|
||||
}
|
||||
trace!("Packets sent!");
|
||||
drop(lock);
|
||||
}
|
||||
|
||||
{
|
||||
let mut lock = CLIENT_MOD_PROGRESS.lock().await;
|
||||
lock.insert(self.id, mod_id as isize);
|
||||
}
|
||||
}
|
||||
_ => error!("Unknown packet! {:?}", packet),
|
||||
}
|
||||
}
|
||||
}
|
||||
self.state = ClientState::None;
|
||||
trace!("Done syncing! Sending map name...");
|
||||
self.write_packet(Packet::Raw(RawPacket::from_str(&format!(
|
||||
"M{}",
|
||||
config.general.map
|
||||
))))
|
||||
.await?;
|
||||
trace!("Map name sent!");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// This function should never block. It should simply check if there's a
|
||||
/// packet, and then and only then should it read it. If this were to block, the server
|
||||
/// would come to a halt until this function unblocks.
|
||||
pub async fn process(&mut self) -> anyhow::Result<Option<RawPacket>> {
|
||||
if let Some(packet) = self.read_packet().await? {
|
||||
return Ok(Some(packet));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub async fn process_blocking(&mut self) -> anyhow::Result<Option<RawPacket>> {
|
||||
if let Some(packet) = self.read_packet_waiting().await? {
|
||||
return Ok(Some(packet));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub fn disconnect(&mut self) {
|
||||
self.state = ClientState::Disconnect;
|
||||
}
|
||||
|
||||
pub async fn kick(&mut self, msg: &str) {
|
||||
// let _ = self.socket.writable().await;
|
||||
// let _ = self.write_packet(Packet::Raw(RawPacket::from_str(&format!("K{}", msg)))).await;
|
||||
// self.disconnect();
|
||||
let _ = self
|
||||
.write_packet(Packet::Raw(RawPacket::from_str(&format!("K{}", msg))))
|
||||
.await;
|
||||
self.disconnect();
|
||||
}
|
||||
|
||||
pub fn get_userdata(&self) -> UserData {
|
||||
self.info.as_ref().unwrap().clone()
|
||||
}
|
||||
|
||||
// Panics when userdata is not set!
|
||||
pub fn get_name(&self) -> &str {
|
||||
&self.info.as_ref().unwrap().username
|
||||
}
|
||||
|
||||
pub fn get_id(&self) -> u8 {
|
||||
self.id
|
||||
}
|
||||
|
||||
// Panics when userdata is not set!
|
||||
pub fn get_roles(&self) -> &str {
|
||||
&self.info.as_ref().unwrap().roles
|
||||
}
|
||||
|
||||
pub fn register_car(&mut self, car: Car) -> u8 {
|
||||
let mut free_num = 0;
|
||||
for (num, _) in &self.cars {
|
||||
if num == &free_num {
|
||||
free_num += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.cars.push((free_num, car));
|
||||
free_num
|
||||
}
|
||||
|
||||
pub fn unregister_car(&mut self, car_id: u8) {
|
||||
let prev_len = self.cars.len();
|
||||
self.cars.retain(|(id, _)| id != &car_id);
|
||||
if prev_len == self.cars.len() {
|
||||
error!(
|
||||
"Failed to unregister car #{} for client #{}! Ignoring for now...",
|
||||
car_id, self.id
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_car_mut(&mut self, mut car_id: u8) -> Option<&mut Car> {
|
||||
for (num, car) in &mut self.cars {
|
||||
if num == &mut car_id {
|
||||
return Some(car);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
async fn read_raw(&mut self, count: usize) -> anyhow::Result<Vec<u8>> {
|
||||
let mut b = vec![0u8; count];
|
||||
self.socket.read_exact(&mut b).await?;
|
||||
Ok(b)
|
||||
}
|
||||
|
||||
async fn read_packet_waiting(&mut self) -> anyhow::Result<Option<RawPacket>> {
|
||||
let start = std::time::Instant::now();
|
||||
'wait: loop {
|
||||
if let Some(packet) = self.read_packet().await? {
|
||||
return Ok(Some(packet));
|
||||
}
|
||||
if start.elapsed().as_secs() >= 5 {
|
||||
break 'wait;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
|
||||
}
|
||||
Err(ClientError::ConnectionTimeout.into())
|
||||
}
|
||||
|
||||
/// Must be non-blocking
|
||||
async fn read_packet(&mut self) -> anyhow::Result<Option<RawPacket>> {
|
||||
let mut header = [0u8; 4];
|
||||
match self.socket.try_read(&mut header) {
|
||||
Ok(0) => {
|
||||
error!("Socket is readable, yet has 0 bytes to read! Disconnecting client...");
|
||||
self.disconnect();
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(_n) => {}
|
||||
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
|
||||
return Ok(None);
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
|
||||
let expected_size = u32::from_le_bytes(header) as usize;
|
||||
let mut data = Vec::new();
|
||||
let mut tmp_data = vec![0u8; expected_size];
|
||||
let mut data_size = 0;
|
||||
while data_size < expected_size {
|
||||
match self.socket.try_read(&mut tmp_data) {
|
||||
Ok(0) => {
|
||||
error!("Socket is readable, yet has 0 bytes to read! Disconnecting client...");
|
||||
self.disconnect();
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(n) => {
|
||||
data_size += n;
|
||||
data.extend_from_slice(&tmp_data[..n]);
|
||||
},
|
||||
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
|
||||
// debug!("Packet appears to be ready, yet can't be read yet!");
|
||||
// self.socket.read(&mut data).await?;
|
||||
return Ok(None);
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Some(RawPacket {
|
||||
header: data_size as u32,
|
||||
data: data[..data_size].to_vec(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Blocking write
|
||||
pub async fn write_packet(&mut self, packet: Packet) -> anyhow::Result<()> {
|
||||
let mut lock = self.write_half.lock().await;
|
||||
lock.writable().await?;
|
||||
trace!("Sending packet!");
|
||||
if let Err(e) = tcp_write(lock.deref_mut(), packet).await {
|
||||
error!("{:?}", e);
|
||||
}
|
||||
trace!("Packet sent!");
|
||||
drop(lock);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn queue_packet(&self, packet: Packet) {
|
||||
// TODO: If packet gets lost, put it back at the front of the queue?
|
||||
let _ = self.write_runtime_sender.send(packet).await;
|
||||
}
|
||||
|
||||
pub async fn trigger_client_event<S: Into<String>, D: Into<String>>(&self, event_name: S, data: D) {
|
||||
let event_name = event_name.into();
|
||||
let data = data.into();
|
||||
debug!("Calling client event '{}' with data '{}'", event_name, data);
|
||||
let packet_data = format!("E:{}:{}", event_name, data);
|
||||
self.queue_packet(Packet::Raw(RawPacket::from_str(&packet_data))).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ClientError {
|
||||
AuthenticateError,
|
||||
ConnectionTimeout,
|
||||
IsDownloader,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ClientError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
|
||||
write!(f, "{:?}", self)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ClientError {}
|
||||
|
||||
#[async_trait]
|
||||
trait Writable {
|
||||
async fn writable(&self) -> std::io::Result<()>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Writable for TcpStream {
|
||||
async fn writable(&self) -> std::io::Result<()> {
|
||||
self.writable().await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Writable for OwnedWriteHalf {
|
||||
async fn writable(&self) -> std::io::Result<()> {
|
||||
self.writable().await
|
||||
}
|
||||
}
|
||||
|
||||
async fn tcp_write<W: AsyncWriteExt + Writable + std::marker::Unpin>(
|
||||
w: &mut W,
|
||||
mut packet: Packet,
|
||||
) -> anyhow::Result<()> {
|
||||
let compressed = match packet.get_code() {
|
||||
Some('O') => true,
|
||||
Some('T') => true,
|
||||
_ => packet.get_data().len() > 400,
|
||||
};
|
||||
|
||||
if compressed {
|
||||
let mut compressed: Vec<u8> = Vec::with_capacity(100_000);
|
||||
let mut compressor = flate2::Compress::new(flate2::Compression::best(), true);
|
||||
compressor.compress_vec(
|
||||
packet.get_data(),
|
||||
&mut compressed,
|
||||
flate2::FlushCompress::Sync,
|
||||
)?;
|
||||
let mut new_data = "ABG:".as_bytes()[..4].to_vec();
|
||||
new_data.append(&mut compressed);
|
||||
packet.set_header(new_data.len() as u32);
|
||||
packet.set_data(new_data);
|
||||
}
|
||||
|
||||
tcp_write_raw(w, packet).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn tcp_write_raw<W: AsyncWriteExt + Writable + std::marker::Unpin>(
|
||||
w: &mut W,
|
||||
mut packet: Packet,
|
||||
) -> anyhow::Result<()> {
|
||||
let mut raw_data: Vec<u8> = packet.get_header().to_le_bytes().to_vec();
|
||||
raw_data.extend_from_slice(packet.get_data());
|
||||
w.writable().await?;
|
||||
w.write(&raw_data).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn tcp_send_file<W: AsyncWriteExt + Writable + std::marker::Unpin>(
|
||||
w: &mut W,
|
||||
file_name: String,
|
||||
) -> anyhow::Result<()> {
|
||||
debug!("Sending file '{}'", file_name);
|
||||
tcp_write(w, Packet::Raw(RawPacket::from_str("KYou have not downloaded the mod manually!"))).await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::{
|
||||
tcp::{OwnedReadHalf, OwnedWriteHalf},
|
||||
TcpStream,
|
||||
};
|
||||
|
||||
pub async fn handle_http_get(socket: TcpStream) {
|
||||
let (read_half, write_half) = socket.into_split();
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn read_get_request(socket: &mut OwnedReadHalf) {
|
||||
todo!()
|
||||
}
|
||||
+1309
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,144 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Packet {
|
||||
Raw(RawPacket),
|
||||
Notification(NotificationPacket),
|
||||
}
|
||||
|
||||
impl Packet {
|
||||
pub fn get_header(&self) -> u32 {
|
||||
match self {
|
||||
Self::Raw(raw) => raw.header,
|
||||
Self::Notification(msg) => self.get_data().len() as u32,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_data(&self) -> &[u8] {
|
||||
match self {
|
||||
Self::Raw(raw) => &raw.data,
|
||||
Self::Notification(p) => p.0.as_bytes(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_code(&self) -> Option<char> {
|
||||
match self {
|
||||
Self::Raw(raw) => raw.data.get(0).map(|c| *c as char),
|
||||
Self::Notification(_) => Some('J'),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_data(&mut self, data: Vec<u8>) {
|
||||
match self {
|
||||
Self::Raw(raw) => raw.data = data,
|
||||
Self::Notification(_) => todo!(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_header(&mut self, header: u32) {
|
||||
match self {
|
||||
Self::Raw(raw) => raw.header = header,
|
||||
Self::Notification(_) => todo!(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn data_as_string(&self) -> String {
|
||||
String::from_utf8_lossy(&self.get_data()).to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct NotificationPacket(String);
|
||||
|
||||
impl NotificationPacket {
|
||||
pub fn new<S: Into<String>>(msg: S) -> Self {
|
||||
Self(format!("J{}", msg.into()))
|
||||
}
|
||||
pub fn player_welcome<S: Into<String>>(msg: S) -> Self {
|
||||
Self(format!("JWelcome {}!", msg.into()))
|
||||
}
|
||||
pub fn player_left<S: Into<String>>(msg: S) -> Self {
|
||||
Self(format!("L{} left the server!", msg.into()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Protocol:
|
||||
/// Header: 4 bytes, contains data size
|
||||
/// Data: Contains packet data
|
||||
#[derive(Clone)]
|
||||
pub struct RawPacket {
|
||||
pub header: u32,
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
impl RawPacket {
|
||||
pub fn from_code(code: char) -> Self {
|
||||
Self {
|
||||
header: 1,
|
||||
data: vec![code as u8],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_data(data: Vec<u8>) -> Self {
|
||||
Self {
|
||||
header: data.len() as u32,
|
||||
data,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_str(str_data: &str) -> Self {
|
||||
let data = str_data.as_bytes().to_vec();
|
||||
Self {
|
||||
header: data.len() as u32,
|
||||
data: data,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn data_as_string(&self) -> String {
|
||||
String::from_utf8_lossy(&self.data).to_string()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for RawPacket {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
|
||||
write!(
|
||||
f,
|
||||
"Header: `{:?}` - Bytes: `{:?}` - String: `{}`",
|
||||
self.header,
|
||||
self.data,
|
||||
self.data_as_string()
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Serialize, Deserialize)]
|
||||
pub struct RespawnPacketData {
|
||||
pub pos: RespawnPacketDataPos,
|
||||
pub rot: RespawnPacketDataRot,
|
||||
}
|
||||
|
||||
#[derive(Default, Serialize, Deserialize)]
|
||||
pub struct RespawnPacketDataPos {
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
pub z: f64,
|
||||
}
|
||||
|
||||
#[derive(Default, Serialize, Deserialize)]
|
||||
pub struct RespawnPacketDataRot {
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
pub z: f64,
|
||||
pub w: f64,
|
||||
}
|
||||
|
||||
#[derive(Default, Serialize, Deserialize)]
|
||||
pub struct TransformPacket {
|
||||
pub rvel: [f64; 3],
|
||||
pub tim: f64,
|
||||
pub pos: [f64; 3],
|
||||
pub ping: f64,
|
||||
pub rot: [f64; 4],
|
||||
pub vel: [f64; 3],
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
use super::{
|
||||
Backend,
|
||||
ServerBoundPluginEvent,
|
||||
PluginBoundPluginEvent,
|
||||
ScriptEvent,
|
||||
Argument
|
||||
};
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::collections::HashMap;
|
||||
|
||||
use tokio::sync::mpsc::{Sender, Receiver};
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
use mlua::prelude::*;
|
||||
use mlua::{UserData, UserDataMethods, Value, Function, Variadic};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Context {
|
||||
tx: Arc<Sender<ServerBoundPluginEvent>>,
|
||||
|
||||
handlers: Arc<Mutex<HashMap<String, String>>>,
|
||||
}
|
||||
|
||||
impl Context {
|
||||
fn new(tx: Arc<Sender<ServerBoundPluginEvent>>) -> Self {
|
||||
Self {
|
||||
tx,
|
||||
|
||||
handlers: Arc::new(Mutex::new(HashMap::new())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> FromLua<'lua> for Context {
|
||||
fn from_lua(value: Value<'lua>, _: &'lua Lua) -> LuaResult<Self> {
|
||||
match value {
|
||||
Value::UserData(ud) => Ok(ud.borrow::<Self>()?.clone()),
|
||||
_ => unreachable!()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl UserData for Context {
|
||||
fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) {
|
||||
// Implement all the API functions here
|
||||
|
||||
methods.add_function("RegisterEventHandler", |lua, (event_name, handler_name): (String, String)| {
|
||||
debug!("Event handler registered: {} (EVENT) = {} (LUA)", event_name, handler_name);
|
||||
let me: Context = lua.globals().get("MP")?;
|
||||
me.handlers.lock().expect("Lock is poisoned!").insert(event_name, handler_name);
|
||||
Ok(())
|
||||
});
|
||||
|
||||
methods.add_function("GetServerVersion", |_lua, ()| {
|
||||
Ok((3, 3, 0))
|
||||
});
|
||||
|
||||
methods.add_function("GetPlayerCount", |lua, ()| {
|
||||
let me: Context = lua.globals().get("MP")?;
|
||||
let (tx, rx) = oneshot::channel();
|
||||
if let Err(e) = me.tx.blocking_send(ServerBoundPluginEvent::RequestPlayerCount(tx)) {
|
||||
error!("Failed to send packet: {:?}", e);
|
||||
}
|
||||
let message = rx.blocking_recv();
|
||||
if let Ok(message) = message {
|
||||
if let PluginBoundPluginEvent::PlayerCount(player_count) = message {
|
||||
Ok(player_count)
|
||||
} else {
|
||||
unreachable!() // This really should never be reachable
|
||||
}
|
||||
} else {
|
||||
todo!("Receiving a response from the server failed! How?")
|
||||
}
|
||||
});
|
||||
|
||||
methods.add_function("GetPlayers", |lua, ()| {
|
||||
let me: Context = lua.globals().get("MP")?;
|
||||
let (tx, rx) = oneshot::channel();
|
||||
if let Err(e) = me.tx.blocking_send(ServerBoundPluginEvent::RequestPlayers(tx)) {
|
||||
error!("Failed to send packet: {:?}", e);
|
||||
}
|
||||
let message = rx.blocking_recv();
|
||||
if let Ok(message) = message {
|
||||
if let PluginBoundPluginEvent::Players(players) = message {
|
||||
let table = lua.create_table()?;
|
||||
for (id, name) in players {
|
||||
table.set(id, name)?;
|
||||
}
|
||||
Ok(table)
|
||||
} else {
|
||||
unreachable!() // This really should never be reachable
|
||||
}
|
||||
} else {
|
||||
todo!("Receiving a response from the server failed! How?")
|
||||
}
|
||||
});
|
||||
|
||||
methods.add_function("GetPlayerIdentifiers", |lua, (id,): (u8,)| {
|
||||
let me: Context = lua.globals().get("MP")?;
|
||||
let (tx, rx) = oneshot::channel();
|
||||
if let Err(e) = me.tx.blocking_send(ServerBoundPluginEvent::RequestPlayerIdentifiers((id, tx))) {
|
||||
error!("Failed to send packet: {:?}", e);
|
||||
}
|
||||
let message = rx.blocking_recv();
|
||||
if let Ok(message) = message {
|
||||
match message {
|
||||
PluginBoundPluginEvent::PlayerIdentifiers(identifiers) => {
|
||||
let table = lua.create_table()?;
|
||||
table.set("id", identifiers.ip)?;
|
||||
table.set("beammp_id", identifiers.beammp_id)?;
|
||||
Ok(Value::Table(table))
|
||||
},
|
||||
PluginBoundPluginEvent::None => Ok(Value::Nil),
|
||||
_ => unreachable!() // This should really never be reachable
|
||||
}
|
||||
} else {
|
||||
todo!("Receiving a response from the server failed! How?")
|
||||
}
|
||||
});
|
||||
|
||||
methods.add_function("GetPlayerName", |lua, (id,): (u8,)| {
|
||||
let me: Context = lua.globals().get("MP")?;
|
||||
// We can simply request all player names and pick the one we need
|
||||
let (tx, rx) = oneshot::channel();
|
||||
if let Err(e) = me.tx.blocking_send(ServerBoundPluginEvent::RequestPlayers(tx)) {
|
||||
error!("Failed to send packet: {:?}", e);
|
||||
}
|
||||
let message = rx.blocking_recv();
|
||||
if let Ok(message) = message {
|
||||
if let PluginBoundPluginEvent::Players(players) = message {
|
||||
let mut name = None;
|
||||
'search: for (pid, pname) in players {
|
||||
if pid == id {
|
||||
name = Some(pname);
|
||||
break 'search;
|
||||
}
|
||||
}
|
||||
Ok(name)
|
||||
} else {
|
||||
unreachable!() // This really should never be reachable
|
||||
}
|
||||
} else {
|
||||
todo!("Receiving a response from the server failed! How?")
|
||||
}
|
||||
});
|
||||
|
||||
methods.add_function("GetPlayerVehicles", |lua, (id,): (u8,)| {
|
||||
let me: Context = lua.globals().get("MP")?;
|
||||
let (tx, rx) = oneshot::channel();
|
||||
if let Err(e) = me.tx.blocking_send(ServerBoundPluginEvent::RequestPlayerVehicles((id, tx))) {
|
||||
error!("Failed to send packet: {:?}", e);
|
||||
}
|
||||
let message = rx.blocking_recv();
|
||||
if let Ok(message) = message {
|
||||
if let PluginBoundPluginEvent::PlayerVehicles(vehicles) = message {
|
||||
let table = lua.create_table()?;
|
||||
for (vid, veh_json) in vehicles {
|
||||
table.set(vid, veh_json)?;
|
||||
}
|
||||
Ok(table)
|
||||
} else {
|
||||
unreachable!() // This really should never be reachable
|
||||
}
|
||||
} else {
|
||||
todo!("Receiving a response from the server failed! How?")
|
||||
}
|
||||
});
|
||||
|
||||
methods.add_function("GetPositionRaw", |lua, (pid, vid): (u8, u8)| {
|
||||
let me: Context = lua.globals().get("MP")?;
|
||||
let (tx, rx) = oneshot::channel();
|
||||
if let Err(e) = me.tx.blocking_send(ServerBoundPluginEvent::RequestPositionRaw((pid, vid, tx))) {
|
||||
error!("Failed to send packet: {:?}", e);
|
||||
}
|
||||
let message = rx.blocking_recv();
|
||||
if let Ok(message) = message {
|
||||
match message {
|
||||
PluginBoundPluginEvent::PositionRaw(pos_raw) => {
|
||||
let pos_table = lua.create_table()?;
|
||||
pos_table.set("x", pos_raw.pos[0])?;
|
||||
pos_table.set("y", pos_raw.pos[1])?;
|
||||
pos_table.set("z", pos_raw.pos[2])?;
|
||||
|
||||
let rot_table = lua.create_table()?;
|
||||
pos_table.set("x", pos_raw.rot[0])?;
|
||||
pos_table.set("y", pos_raw.rot[1])?;
|
||||
pos_table.set("z", pos_raw.rot[2])?;
|
||||
pos_table.set("w", pos_raw.rot[3])?;
|
||||
|
||||
let table = lua.create_table()?;
|
||||
table.set("pos", pos_table)?;
|
||||
table.set("rot", rot_table)?;
|
||||
Ok(Value::Table(table))
|
||||
},
|
||||
PluginBoundPluginEvent::None => Ok(Value::Nil),
|
||||
_ => unreachable!() // This really should never be reachable
|
||||
}
|
||||
} else {
|
||||
todo!("Receiving a response from the server failed! How?")
|
||||
}
|
||||
});
|
||||
|
||||
methods.add_function("SendChatMessage", |lua, (id, msg): (isize, String)| {
|
||||
let me: Context = lua.globals().get("MP")?;
|
||||
if let Err(e) = me.tx.blocking_send(ServerBoundPluginEvent::SendChatMessage((id, msg))) {
|
||||
error!("Failed to send packet: {:?}", e);
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
|
||||
methods.add_function("GetOSName", |lua, ()| {
|
||||
Ok(std::env::consts::OS)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub struct BackendLua {
|
||||
lua: Lua,
|
||||
}
|
||||
|
||||
impl BackendLua {
|
||||
pub fn new() -> Self {
|
||||
let lua = Lua::new();
|
||||
|
||||
Self {
|
||||
lua,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Backend for BackendLua {
|
||||
fn load(&mut self, code: String) -> anyhow::Result<()> {
|
||||
self.lua.load(code).exec().map_err(|e| { error!("[LUA] {:?}", e); e })?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_api(&mut self, tx: Arc<Sender<ServerBoundPluginEvent>>) -> anyhow::Result<()> {
|
||||
let print_fn = self.lua.create_function(|_lua, (msg,): (String,)| {
|
||||
info!("[LUA] {}", msg);
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
let api = Context::new(tx);
|
||||
|
||||
let globals = self.lua.globals();
|
||||
globals.set("MP", api)?;
|
||||
globals.set("print", print_fn)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn call_event_handler(&mut self, event: ScriptEvent, resp: Option<oneshot::Sender<Argument>>) {
|
||||
let (event_name, args) = match event {
|
||||
ScriptEvent::OnPluginLoaded => ("onInit", vec![]),
|
||||
ScriptEvent::OnShutdown => ("onShutdown", vec![]),
|
||||
|
||||
ScriptEvent::OnPlayerAuthenticated { name, role, is_guest, identifiers } => ("onPlayerAuth", vec![Argument::String(name), Argument::String(role), Argument::Boolean(is_guest), Argument::Table(identifiers.to_map())]),
|
||||
ScriptEvent::OnPlayerConnecting { pid } => ("onPlayerConnecting", vec![Argument::Integer(pid as i64)]),
|
||||
ScriptEvent::OnPlayerJoining { pid } => ("onPlayerJoining", vec![Argument::Integer(pid as i64)]),
|
||||
|
||||
ScriptEvent::OnPlayerDisconnect { pid, name } => ("onPlayerDisconnect", vec![Argument::Integer(pid as i64), Argument::String(name)]),
|
||||
|
||||
ScriptEvent::OnVehicleSpawn { pid, vid, car_data } => ("onVehicleSpawn", vec![Argument::Integer(pid as i64), Argument::Integer(vid as i64), Argument::String(car_data)]),
|
||||
ScriptEvent::OnVehicleEdited { pid, vid, car_data } => ("onVehicleEdited", vec![Argument::Integer(pid as i64), Argument::Integer(vid as i64), Argument::String(car_data)]),
|
||||
ScriptEvent::OnVehicleDeleted { pid, vid } => ("onVehicleDeleted", vec![Argument::Integer(pid as i64), Argument::Integer(vid as i64)]),
|
||||
ScriptEvent::OnVehicleReset { pid, vid, car_data } => ("onVehicleReset", vec![Argument::Integer(pid as i64), Argument::Integer(vid as i64), Argument::String(car_data)]),
|
||||
|
||||
ScriptEvent::OnChatMessage { pid, name, message } => ("onChatMessage", vec![Argument::Integer(pid as i64), Argument::String(name), Argument::String(message)]),
|
||||
};
|
||||
|
||||
let mut ret = Value::Number(-1f64);
|
||||
// TODO: Error handling
|
||||
{
|
||||
let ctx: Context = self.lua.globals().get("MP").expect("MP is missing!");
|
||||
let lock = ctx.handlers.lock().expect("Mutex is poisoned!");
|
||||
if let Some(handler_name) = lock.get(event_name) {
|
||||
let func: LuaResult<Function> = self.lua.globals().get(handler_name.clone());
|
||||
if let Ok(func) = func {
|
||||
let mapped_args = args.into_iter().map(|arg| {
|
||||
arg_to_value(&self.lua, arg)
|
||||
}).filter(|v| v.is_some());
|
||||
match func.call::<_, Value>(Variadic::from_iter(mapped_args)) {
|
||||
Ok(res) => { trace!("fn ret: {:?}", res); ret = res; }
|
||||
Err(e) => {
|
||||
error!("[LUA] {}", e);
|
||||
ret = Value::Number(-1f64);
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
debug!("sending result...");
|
||||
if let Some(resp) = resp {
|
||||
let arg = value_to_arg(ret);
|
||||
resp.send(arg).expect("Failed to send!");
|
||||
}
|
||||
debug!("call_event_handler done");
|
||||
}
|
||||
}
|
||||
|
||||
fn value_to_arg(value: Value) -> Argument {
|
||||
match value {
|
||||
Value::Boolean(b) => Argument::Boolean(b),
|
||||
Value::Integer(i) => Argument::Integer(i),
|
||||
Value::Number(f) => Argument::Number(f as f32),
|
||||
Value::String(s) => Argument::String(s.to_string_lossy().to_string()),
|
||||
_ => Argument::Number(-1f32),
|
||||
}
|
||||
}
|
||||
|
||||
fn arg_to_value(lua: &Lua, arg: Argument) -> Option<Value> {
|
||||
match arg {
|
||||
Argument::String(s) => if let Ok(lua_str) = lua.create_string(&s) { Some(Value::String(lua_str)) } else { None },
|
||||
Argument::Boolean(b) => Some(Value::Boolean(b)),
|
||||
Argument::Number(f) => Some(Value::Number(f as f64)),
|
||||
Argument::Integer(i) => Some(Value::Integer(i as i64)),
|
||||
Argument::Table(t) => {
|
||||
if let Ok(table) = lua.create_table() {
|
||||
for (key, value) in t {
|
||||
if let Some(v) = arg_to_value(lua, value) {
|
||||
if let Err(e) = table.set(key, v) {
|
||||
error!("[LUA] Error occured trying to put data into table: {:?}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(Value::Table(table))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
pub mod backend_lua;
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::collections::HashMap;
|
||||
use tokio::runtime::Runtime;
|
||||
use tokio::sync::mpsc::{self, Sender, Receiver};
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
/// NOTE: Send is required as the backend is constructed on the main thread and sent over.
|
||||
/// Even if we construct it inside the runtime however, because of tokio, we would
|
||||
// still have to require Send as the runtime might run on different threads (?)
|
||||
pub trait Backend: Send {
|
||||
fn load(&mut self, code: String) -> anyhow::Result<()>;
|
||||
fn load_api(&mut self, tx: Arc<Sender<ServerBoundPluginEvent>>) -> anyhow::Result<()>;
|
||||
|
||||
fn call_event_handler(&mut self, event: ScriptEvent, resp: Option<oneshot::Sender<Argument>>);
|
||||
}
|
||||
|
||||
// TODO: This is quite focused on Lua right now, perhaps in the future we want to modify this list
|
||||
// to be more versatile?
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Argument {
|
||||
String(String),
|
||||
Boolean(bool),
|
||||
Number(f32),
|
||||
Integer(i64),
|
||||
Table(HashMap<String, Argument>),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct PlayerIdentifiers {
|
||||
pub ip: String,
|
||||
pub beammp_id: String,
|
||||
}
|
||||
|
||||
impl PlayerIdentifiers {
|
||||
pub fn to_map(&self) -> HashMap<String, Argument> {
|
||||
let mut m = HashMap::new();
|
||||
m.insert(String::from("ip"), Argument::String(self.ip.clone()));
|
||||
m.insert(String::from("beammp"), Argument::String(self.beammp_id.clone()));
|
||||
m
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct PositionRaw {
|
||||
pub pos: [f32; 3],
|
||||
pub rot: [f32; 4],
|
||||
}
|
||||
|
||||
impl PositionRaw {
|
||||
pub fn to_map(&self) -> HashMap<String, Argument> {
|
||||
let mut pm = HashMap::new();
|
||||
pm.insert(String::from("x"), Argument::Number(self.pos[0]));
|
||||
pm.insert(String::from("y"), Argument::Number(self.pos[1]));
|
||||
pm.insert(String::from("z"), Argument::Number(self.pos[2]));
|
||||
|
||||
let mut rm = HashMap::new();
|
||||
rm.insert(String::from("x"), Argument::Number(self.rot[0]));
|
||||
rm.insert(String::from("y"), Argument::Number(self.rot[1]));
|
||||
rm.insert(String::from("z"), Argument::Number(self.rot[2]));
|
||||
rm.insert(String::from("w"), Argument::Number(self.rot[3]));
|
||||
|
||||
let mut m = HashMap::new();
|
||||
m.insert(String::from("pos"), Argument::Table(pm));
|
||||
m.insert(String::from("rot"), Argument::Table(rm));
|
||||
m
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ScriptEvent {
|
||||
OnPluginLoaded,
|
||||
OnShutdown,
|
||||
|
||||
// TODO: Because of limitations in how we accept clients, onPlayerAuth runs after mod downloading and syncing
|
||||
// has already happened. With some reworking, this can be avoided, but it's not easy.
|
||||
// This is quite important however, because otherwise mod downloads will get triggered
|
||||
// constantly even when someone isn't allowed to join!
|
||||
OnPlayerAuthenticated { name: String, role: String, is_guest: bool, identifiers: PlayerIdentifiers },
|
||||
// TODO: See the comment above, this results in these 2 events being useless for now.
|
||||
// I've simply left them in for backwards compatibility for now!
|
||||
OnPlayerConnecting { pid: u8 },
|
||||
OnPlayerJoining { pid: u8 },
|
||||
|
||||
OnPlayerDisconnect { pid: u8, name: String },
|
||||
|
||||
OnVehicleSpawn { pid: u8, vid: u8, car_data: String },
|
||||
OnVehicleEdited { pid: u8, vid: u8, car_data: String },
|
||||
OnVehicleDeleted { pid: u8, vid: u8 },
|
||||
OnVehicleReset { pid: u8, vid: u8, car_data: String },
|
||||
|
||||
OnChatMessage { pid: u8, name: String, message: String },
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum PluginBoundPluginEvent {
|
||||
None,
|
||||
|
||||
CallEventHandler((ScriptEvent, Option<oneshot::Sender<Argument>>)),
|
||||
|
||||
PlayerCount(usize),
|
||||
Players(HashMap<u8, String>),
|
||||
PlayerIdentifiers(PlayerIdentifiers),
|
||||
|
||||
PlayerVehicles(HashMap<u8, String>),
|
||||
PositionRaw(PositionRaw),
|
||||
}
|
||||
|
||||
// TODO: Perhaps it would be nice to ensure each sender can only sned specifically what it needs to.
|
||||
// Purely to ensure type safety and slightly cleaner code on the backend implementation side.
|
||||
#[derive(Debug)]
|
||||
pub enum ServerBoundPluginEvent {
|
||||
PluginLoaded,
|
||||
|
||||
RequestPlayerCount(oneshot::Sender<PluginBoundPluginEvent>),
|
||||
RequestPlayers(oneshot::Sender<PluginBoundPluginEvent>),
|
||||
RequestPlayerIdentifiers((u8, oneshot::Sender<PluginBoundPluginEvent>)),
|
||||
|
||||
RequestPlayerVehicles((u8, oneshot::Sender<PluginBoundPluginEvent>)),
|
||||
RequestPositionRaw((u8, u8, oneshot::Sender<PluginBoundPluginEvent>)),
|
||||
|
||||
SendChatMessage((isize, String)),
|
||||
}
|
||||
|
||||
pub struct Plugin {
|
||||
runtime: Runtime,
|
||||
tx: Sender<PluginBoundPluginEvent>,
|
||||
rx: Receiver<ServerBoundPluginEvent>,
|
||||
}
|
||||
|
||||
impl Plugin {
|
||||
pub fn new(mut backend: Box<dyn Backend>, src: String) -> anyhow::Result<Self> {
|
||||
let runtime = Runtime::new().expect("Failed to create a tokio Runtime!");
|
||||
let (pb_tx, mut pb_rx) = mpsc::channel(1_000);
|
||||
let (sb_tx, sb_rx) = mpsc::channel(1_000);
|
||||
let sb_tx = Arc::new(sb_tx);
|
||||
runtime.spawn_blocking(move || {
|
||||
if backend.load_api(sb_tx.clone()).is_ok() {
|
||||
if backend.load(src).is_ok() {
|
||||
if sb_tx.blocking_send(ServerBoundPluginEvent::PluginLoaded).is_err() {
|
||||
error!("Plugin communication channels somehow already closed!");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
loop {
|
||||
if let Some(message) = pb_rx.blocking_recv() {
|
||||
match message {
|
||||
PluginBoundPluginEvent::CallEventHandler((event, resp)) => {
|
||||
backend.call_event_handler(event, resp);
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
} else {
|
||||
error!("Event receiver has closed!"); // TODO: We probably want to display the plugin name here too lol
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(Self {
|
||||
runtime,
|
||||
tx: pb_tx,
|
||||
rx: sb_rx,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn close(mut self) {
|
||||
let (tx, mut rx) = oneshot::channel();
|
||||
self.send_event(PluginBoundPluginEvent::CallEventHandler((ScriptEvent::OnShutdown, Some(tx)))).await;
|
||||
let _ = rx.await; // We just wait for it to finish shutting down
|
||||
self.runtime.shutdown_background();
|
||||
}
|
||||
|
||||
// TODO: For performance I think we can turn this into an iterator instead of first allocating
|
||||
// a full vector?
|
||||
pub fn get_events(&mut self) -> Vec<ServerBoundPluginEvent> {
|
||||
let mut events = Vec::new();
|
||||
loop {
|
||||
match self.rx.try_recv() {
|
||||
Ok(event) => events.push(event),
|
||||
Err(mpsc::error::TryRecvError::Disconnected) => break, // TODO: This means the runtime is dead!!! Handle this!!!
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
events
|
||||
}
|
||||
|
||||
// TODO: Handle error when connection is closed, as it means the runtime is down
|
||||
pub async fn send_event(&self, event: PluginBoundPluginEvent) {
|
||||
let _ = self.tx.send(event).await;
|
||||
}
|
||||
}
|
||||
+201
@@ -0,0 +1,201 @@
|
||||
use std::sync::Arc;
|
||||
use std::io::{stdout, Result};
|
||||
use std::collections::VecDeque;
|
||||
use log::Level;
|
||||
|
||||
use crossterm::{
|
||||
event::{self, KeyCode, KeyEventKind, KeyModifiers},
|
||||
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
|
||||
ExecutableCommand,
|
||||
};
|
||||
use ratatui::{
|
||||
prelude::*,
|
||||
widgets::{Paragraph, Block, Borders},
|
||||
};
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::server::ServerStatus;
|
||||
|
||||
pub async fn tui_main(config: Arc<Config>, cmd_tx: mpsc::Sender<Vec<String>>, mut info_rx: mpsc::Receiver<ServerStatus>) {
|
||||
let mut tui = Tui::new().expect("Failed to initialize tui!");
|
||||
|
||||
'app: loop {
|
||||
if tui.update(&cmd_tx, &mut info_rx).await.expect("Failed to run tui.update!") {
|
||||
cmd_tx.send(vec!["exit".to_string()]).await.unwrap();
|
||||
break 'app;
|
||||
}
|
||||
tui.draw().expect("Failed to run tui.draw!");
|
||||
}
|
||||
}
|
||||
|
||||
struct Tui {
|
||||
terminal: Terminal<CrosstermBackend<std::io::Stdout>>,
|
||||
|
||||
log_buffer: VecDeque<(Level, String)>,
|
||||
|
||||
history_scroll: usize,
|
||||
input_history: Vec<String>,
|
||||
input: String,
|
||||
|
||||
server_status: ServerStatus,
|
||||
}
|
||||
|
||||
impl Drop for Tui {
|
||||
fn drop(&mut self) {
|
||||
if let Err(e) = self.cleanup() {
|
||||
eprintln!("Error occured related to the TUI: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Tui {
|
||||
fn new() -> Result<Self> {
|
||||
stdout().execute(EnterAlternateScreen)?;
|
||||
enable_raw_mode()?;
|
||||
|
||||
let terminal = Terminal::new(CrosstermBackend::new(stdout()))?;
|
||||
|
||||
Ok(Self {
|
||||
terminal,
|
||||
|
||||
log_buffer: VecDeque::new(),
|
||||
|
||||
history_scroll: 0,
|
||||
input_history: Vec::new(),
|
||||
input: String::new(),
|
||||
|
||||
server_status: ServerStatus::default(),
|
||||
})
|
||||
}
|
||||
|
||||
fn cleanup(&self) -> Result<()> {
|
||||
stdout().execute(LeaveAlternateScreen)?;
|
||||
disable_raw_mode()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn update(&mut self, cmd_tx: &mpsc::Sender<Vec<String>>, info_rx: &mut mpsc::Receiver<ServerStatus>) -> Result<bool> {
|
||||
for (level, msg) in crate::logger::drain_log_buffer().await {
|
||||
self.log_buffer.push_front((level, msg));
|
||||
if self.log_buffer.len() > 100 {
|
||||
self.log_buffer.pop_back();
|
||||
}
|
||||
}
|
||||
|
||||
match info_rx.try_recv() {
|
||||
Ok(status) => self.server_status = status,
|
||||
Err(mpsc::error::TryRecvError::Empty) => {},
|
||||
Err(e) => return Ok(true),
|
||||
}
|
||||
|
||||
if event::poll(std::time::Duration::from_millis(16))? {
|
||||
if let event::Event::Key(key) = event::read()? {
|
||||
if key.kind == KeyEventKind::Press {
|
||||
match key.code {
|
||||
KeyCode::Char(c) if key.modifiers.contains(KeyModifiers::CONTROL) => {
|
||||
|
||||
},
|
||||
KeyCode::Char(c) => {
|
||||
let c = if key.modifiers == KeyModifiers::SHIFT { c.to_ascii_uppercase() } else { c };
|
||||
self.input.push(c);
|
||||
self.history_scroll = 0;
|
||||
},
|
||||
KeyCode::Backspace => { self.input.pop(); },
|
||||
KeyCode::Enter => {
|
||||
if self.input.is_empty() == false {
|
||||
let args = self.input.split(" ").map(|s| s.to_string()).collect::<Vec<String>>();
|
||||
if let Err(e) = cmd_tx.send(args.clone()).await {
|
||||
error!("Error occured sending a command to the server! {e}");
|
||||
return Ok(true);
|
||||
}
|
||||
self.input_history.insert(0, self.input.clone());
|
||||
self.input = String::new();
|
||||
if args.get(0) == Some(&"exit".to_string()) {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
},
|
||||
KeyCode::Up => {
|
||||
if self.history_scroll < self.input_history.len() {
|
||||
self.history_scroll += 1;
|
||||
self.input = self.input_history[self.history_scroll - 1].clone();
|
||||
}
|
||||
},
|
||||
KeyCode::Down => {
|
||||
if self.history_scroll > 1 {
|
||||
self.history_scroll -= 1;
|
||||
self.input = self.input_history[self.history_scroll - 1].clone();
|
||||
}
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
fn draw(&mut self) -> Result<()> {
|
||||
self.terminal.draw(|frame| {
|
||||
let area = frame.size();
|
||||
|
||||
let vert_layout = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints(vec![
|
||||
Constraint::Length(area.height - 3),
|
||||
Constraint::Length(3),
|
||||
])
|
||||
.split(area);
|
||||
|
||||
let horiz_layout = Layout::default()
|
||||
.direction(Direction::Horizontal)
|
||||
.constraints(vec![
|
||||
Constraint::Percentage(70),
|
||||
Constraint::Percentage(30),
|
||||
])
|
||||
.split(vert_layout[0]);
|
||||
|
||||
let mut lines = Vec::new();
|
||||
for (i, (level, msg)) in self.log_buffer.iter().enumerate() {
|
||||
if i >= (area.height as usize - 5) { break; }
|
||||
let (level_style, spacer) = match level {
|
||||
Level::Info => (Style::default().green(), " "),
|
||||
Level::Warn => (Style::default().yellow(), " "),
|
||||
Level::Error => (Style::default().red(), ""),
|
||||
Level::Debug => (Style::default().gray(), ""),
|
||||
Level::Trace => (Style::default().cyan(), ""),
|
||||
};
|
||||
lines.push(Line::from(vec![
|
||||
Span::styled("[", Style::default()),
|
||||
Span::styled(format!("{}", level), level_style),
|
||||
Span::styled(format!("]{} {}", spacer, msg), Style::default()),
|
||||
]));
|
||||
}
|
||||
lines.reverse();
|
||||
frame.render_widget(
|
||||
// Paragraph::new("[INFO] info!!!\n[DEBUG] debug!!!!").block(Block::new().borders(Borders::ALL)),
|
||||
Paragraph::new(Text::from(lines)).block(Block::new().borders(Borders::ALL).title("Log")),
|
||||
horiz_layout[0],
|
||||
);
|
||||
|
||||
let mut lines = Vec::new();
|
||||
for (id, name) in &self.server_status.player_list {
|
||||
lines.push(Line::from(format!("{id} - {name}")));
|
||||
}
|
||||
frame.render_widget(
|
||||
Paragraph::new(lines).block(Block::new().borders(Borders::ALL).title("Player List")),
|
||||
horiz_layout[1],
|
||||
);
|
||||
|
||||
frame.render_widget(
|
||||
Paragraph::new(format!(" > {}", self.input)).block(Block::new().borders(Borders::ALL).title("Input")),
|
||||
vert_layout[1],
|
||||
);
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user