move new protocol code into main repo

This commit is contained in:
Lion Kortlepel 2024-01-19 17:45:00 +01:00
parent 3fc74285e6
commit 12ba13d9b4
No known key found for this signature in database
GPG Key ID: 4322FF2B4C71259B
33 changed files with 5979 additions and 0 deletions

5
.clang-format Normal file
View File

@ -0,0 +1,5 @@
---
BasedOnStyle: WebKit
BreakBeforeBraces: Attach
SpaceAfterTemplateKeyword: false
...

154
CMakeLists.txt Normal file
View File

@ -0,0 +1,154 @@
cmake_minimum_required(VERSION 3.16 FATAL_ERROR)
if (WIN32)
set(VCPKG_TARGET_TRIPLET x64-windows-static)
endif()
include(cmake/Vcpkg.cmake) # needs to happen before project()
project(
"BeamMP-Launcher" # replace this
VERSION 2.0.100
LANGUAGES CXX
)
include(cmake/StandardSettings.cmake)
include(cmake/StaticAnalyzers.cmake)
include(cmake/Git.cmake)
add_subdirectory(deps/BeamMP-Protocol)
# below are options which should be changed
### SETTINGS ###
# add all headers (.h, .hpp) to this
set(PRJ_HEADERS
src/Http.h
src/Launcher.h
src/Platform.h
src/Identity.h
src/Version.h
src/Hashing.h
src/Compression.h
src/Config.h
)
# add all source files (.cpp) to this, except the one with main()
set(PRJ_SOURCES
src/Launcher.cpp
src/main.cpp
src/Launcher.cpp
src/PlatformWindows.cpp
src/PlatformLinux.cpp
src/Identity.cpp
src/Http.cpp
src/Version.cpp
src/Hashing.cpp
src/Config.cpp
)
# set the source file containing main()
set(PRJ_MAIN src/main.cpp)
# set the source file containing the test's main
set(PRJ_TEST_MAIN tests/test_main.cpp)
# set include paths not part of libraries
set(PRJ_INCLUDE_DIRS src)
# set compile features (e.g. standard version)
set(PRJ_COMPILE_FEATURES cxx_std_20)
# set #defines (test enable/disable not included here)
set(PRJ_DEFINITIONS CPPHTTPLIB_OPENSSL_SUPPORT)
# add all libraries used by the project (WARNING: also set them in vcpkg.json!)
set(PRJ_LIBRARIES
fmt::fmt
doctest::doctest
Threads::Threads
spdlog::spdlog
httplib::httplib
Boost::system
Boost::iostreams
Boost::thread
cryptopp::cryptopp
ZLIB::ZLIB
OpenSSL::SSL
OpenSSL::Crypto
protocol
zstd::libzstd_static
)
# add dependency find_package calls and similar here
find_package(fmt CONFIG REQUIRED)
find_package(doctest CONFIG REQUIRED)
find_package(spdlog CONFIG REQUIRED)
find_package(httplib CONFIG REQUIRED)
find_package(Boost REQUIRED COMPONENTS system iostreams thread)
find_package(cryptopp CONFIG REQUIRED)
find_package(ZLIB REQUIRED)
find_package(OpenSSL REQUIRED)
find_package(zstd CONFIG REQUIRED)
# to enable multithreading and the Threads::Threads dependency
include(FindThreads)
### END SETTINGS ###
# DONT change anything beyond this point unless you've read the cmake bible and
# swore on it not to bonk up the ci/cd pipelines with your changes.
####################
# enables compile_commands.json for clang-related tools (such as the clang LS)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
# build debug builds by default (if not specified otherwise)
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE "Debug")
endif()
if(UNIX)
# this will allow to use same _DEBUG macro available in both Linux as well as Windows - MSCV environment. Easy to put Debug specific code.
add_compile_options("$<$<CONFIG:DEBUG>:-D_DEBUG>")
endif(UNIX)
include(cmake/CompilerWarnings.cmake)
# set MT library for msvc - this is required (says documentation)
# linux/mac/etc should simply ignore this by default.
message(STATUS "MSVC -> forcing use of statically-linked runtime.")
STRING(REPLACE "/MD" "/MT" CMAKE_CXX_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE})
STRING(REPLACE "/MDd" "/MTd" CMAKE_CXX_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG})
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>DLL")
set(PRJ_DEFINITIONS ${PRJ_DEFINITIONS}
PRJ_VERSION_MAJOR=${PROJECT_VERSION_MAJOR}
PRJ_VERSION_MINOR=${PROJECT_VERSION_MINOR}
PRJ_VERSION_PATCH=${PROJECT_VERSION_PATCH}
PRJ_GIT_HASH="${PRJ_GIT_HASH}"
)
add_executable(${PROJECT_NAME} ${PRJ_HEADERS} ${PRJ_SOURCES} ${PRJ_MAIN})
target_link_libraries(${PROJECT_NAME} ${PRJ_LIBRARIES})
target_include_directories(${PROJECT_NAME} PRIVATE ${PRJ_INCLUDE_DIRS})
target_compile_features(${PROJECT_NAME} PRIVATE ${PRJ_COMPILE_FEATURES})
target_compile_definitions(${PROJECT_NAME} PRIVATE ${PRJ_DEFINITIONS} ${PRJ_WARNINGS}
DOCTEST_CONFIG_DISABLE # disables all test code in the final executable
)
if (WIN32)
target_compile_definitions(${PROJECT_NAME} PRIVATE -DPLATFORM_WINDOWS=1)
else ()
target_compile_definitions(${PROJECT_NAME} PRIVATE -DPLATFORM_LINUX=1)
endif ()
# setup all warnings (from cmake/CompilerWarnings.cmake)
set_project_warnings(${PROJECT_NAME})
if(${PROJECT_NAME}_ENABLE_UNIT_TESTING)
message(STATUS "Unit tests are enabled and will be built as '${PROJECT_NAME}-tests'")
add_executable(${PROJECT_NAME}-tests ${PRJ_HEADERS} ${PRJ_SOURCES} ${PRJ_TEST_MAIN})
target_link_libraries(${PROJECT_NAME}-tests ${PRJ_LIBRARIES})
target_include_directories(${PROJECT_NAME}-tests PRIVATE ${PRJ_INCLUDE_DIRS})
target_compile_features(${PROJECT_NAME}-tests PRIVATE ${PRJ_COMPILE_FEATURES})
target_compile_definitions(${PROJECT_NAME}-tests PRIVATE ${PRJ_DEFINITIONS} ${PRJ_WARNINGS})
set_project_warnings(${PROJECT_NAME}-tests)
endif()

2742
Doxyfile Normal file

File diff suppressed because it is too large Load Diff

661
LICENSE Normal file
View File

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <https://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
<https://www.gnu.org/licenses/>.

119
README.md Normal file
View File

@ -0,0 +1,119 @@
# Base Template for C++ based projects
## How to use
TODO: section on how to initialize with this
## Name and Version
In order to specify the project name, executable name and name of the unit tests executable, edit the CMakeLists.txt.
In there, it says:
```cmake
project(
"MY_PROJECT" # replace this
VERSION 0.1.0
LANGUAGES CXX
)
```
Edit the `MY_PROJECT` to a name that suits your project, and adjust the `VERSION` if necessary.
Further, go into `vcpkg.json` and edit the two lines shown here, similarly to how you did in the CMakeLists.txt:
```json
{
"name": "my-project",
"version-string": "0.1.0",
...
```
Keep in mind the name constraints and requirements for vcpkg.
## Adding source files
To add source files, add them to the following section in the CMakeLists.txt:
```cmake
# add all headers (.h, .hpp) to this
set(PRJ_HEADERS )
# add all source files (.cpp) to this, except the one with main()
set(PRJ_SOURCES )
```
For example, to add `mysource.cpp`, `somefile.cpp` and `myheader.h`, proceed as follows:
```cmake
# add all headers (.h, .hpp) to this
set(PRJ_HEADERS mysource.cpp somefile.cpp)
# add all source files (.cpp) to this, except the one with main()
set(PRJ_SOURCES myheader.h)
```
## Building
To build, run cmake (`bin` will be the output directory, `.` the source directory):
```sh
cmake -S . -B bin
```
This will configure it with all default settings.
Then build with:
```sh
cmake --build bin --parallel
```
## Adding dependencies
First, find your dependency on vcpkg (for example using [this website](https://vcpkg.io/en/packages.html)). For example, you may be looking for lionkor's `commandline` library, and you will find `lionkor-commandline`.
Second, note down the name, in our example `lionkor-commandline`, and add it to the vcpkg.json, like so:
Before:
```json
{
...
"dependencies": [
"fmt",
"doctest"
]
}
```
After:
```json
{
...
"dependencies": [
"fmt",
"doctest",
"lionkor-commandline"
]
}
```
Third, go to CMakeLists.txt and find the following:
```cmake
# add dependency find_package calls and similar here
find_package(fmt CONFIG REQUIRED)
find_package(doctest CONFIG REQUIRED)
...
```
and add your `find_package` call or equivalent below it.
Last, find this section (above the previous):
```cmake
# add all libraries used by the project (WARNING: also set them in vcpkg.json!)
set(PRJ_LIBRARIES
fmt::fmt
...
)
```
and add your library there. The exact expression used here differs from library to library, but should be easy to find in their documentation. When in doubt, it's simply the name of the library.

View File

@ -0,0 +1,113 @@
# from here:
#
# https://github.com/lefticus/cppbestpractices/blob/master/02-Use_the_Tools_Available.md
# Courtesy of Jason Turner
# License here: https://github.com/cpp-best-practices/cppbestpractices/blob/master/LICENSE
#
# This version has been modified by the owners of the current respository.
# Modifications have mostly been marked with "modified" or similar, though this is not
# strictly required.
function(set_project_warnings project_name)
set(MSVC_WARNINGS
/W4 # Baseline reasonable warnings
/w14242 # 'identifier': conversion from 'type1' to 'type1', possible loss
# of data
/w14254 # 'operator': conversion from 'type1:field_bits' to
# 'type2:field_bits', possible loss of data
/w14263 # 'function': member function does not override any base class
# virtual member function
/w14265 # 'classname': class has virtual functions, but destructor is not
# virtual instances of this class may not be destructed correctly
/w14287 # 'operator': unsigned/negative constant mismatch
/we4289 # nonstandard extension used: 'variable': loop control variable
# declared in the for-loop is used outside the for-loop scope
/w14296 # 'operator': expression is always 'boolean_value'
/w14311 # 'variable': pointer truncation from 'type1' to 'type2'
/w14545 # expression before comma evaluates to a function which is missing
# an argument list
/w14546 # function call before comma missing argument list
/w14547 # 'operator': operator before comma has no effect; expected
# operator with side-effect
/w14549 # 'operator': operator before comma has no effect; did you intend
# 'operator'?
/w14555 # expression has no effect; expected expression with side- effect
/w14619 # pragma warning: there is no warning number 'number'
/w14640 # Enable warning on thread un-safe static member initialization
/w14826 # Conversion from 'type1' to 'type_2' is sign-extended. This may
# cause unexpected runtime behavior.
/w14905 # wide string literal cast to 'LPSTR'
/w14906 # string literal cast to 'LPWSTR'
/w14928 # illegal copy-initialization; more than one user-defined
# conversion has been implicitly applied
/permissive- # standards conformance mode for MSVC compiler.
)
set(CLANG_WARNINGS
-Wall
-Wextra # reasonable and standard
-Wshadow # warn the user if a variable declaration shadows one from a
# parent context
-Wnon-virtual-dtor # warn the user if a class with virtual functions has a
# non-virtual destructor. This helps catch hard to
# track down memory errors
-Wold-style-cast # warn for c-style casts
-Wcast-align # warn for potential performance problem casts
-Wunused # warn on anything being unused
-Woverloaded-virtual # warn if you overload (not override) a virtual
# function
-Wpedantic # warn if non-standard C++ is used
-Wconversion # warn on type conversions that may lose data
-Wsign-conversion # warn on sign conversions
-Wnull-dereference # warn if a null dereference is detected
-Wdouble-promotion # warn if float is implicit promoted to double
-Wformat=2 # warn on security issues around functions that format output
# (ie printf)
# modified; added more errors / warnings
# some have been set to be errors, but the option _WARNINGS_AS_ERRORS
# (see below) should still be used in strict pipelines.
-Werror=uninitialized
-Werror=float-equal
-Werror=write-strings
-Werror=strict-aliasing -fstrict-aliasing
-Werror=missing-declarations
-Werror=missing-field-initializers
-Werror=ctor-dtor-privacy
-Werror=switch-default
-Werror=unused-result
-Werror=implicit-fallthrough
-Wmissing-include-dirs
)
if (${PROJECT_NAME}_WARNINGS_AS_ERRORS)
set(CLANG_WARNINGS ${CLANG_WARNINGS} -Werror)
set(MSVC_WARNINGS ${MSVC_WARNINGS} /WX)
endif()
set(GCC_WARNINGS
${CLANG_WARNINGS}
-Wmisleading-indentation # warn if indentation implies blocks where blocks
# do not exist
-Wduplicated-cond # warn if if / else chain has duplicated conditions
-Wduplicated-branches # warn if if / else branches have duplicated code
-Wlogical-op # warn about logical operations being used where bitwise were
# probably wanted
# -Wuseless-cast # warn if you perform a cast to the same type (modified: removed)
)
if(MSVC)
set(PRJ_WARNINGS ${MSVC_WARNINGS})
elseif(CMAKE_CXX_COMPILER_ID MATCHES ".*Clang")
set(PRJ_WARNINGS ${CLANG_WARNINGS})
elseif(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
set(PRJ_WARNINGS ${GCC_WARNINGS})
else()
message(AUTHOR_WARNING "No compiler warnings set for '${CMAKE_CXX_COMPILER_ID}' compiler.")
endif()
target_compile_options(${project_name} PUBLIC ${PRJ_WARNINGS})
if(NOT TARGET ${project_name})
message(AUTHOR_WARNING "${project_name} is not a target, thus no compiler warning were added.")
endif()
endfunction()

26
cmake/Git.cmake Normal file
View File

@ -0,0 +1,26 @@
find_package(Git)
if(${PROJECT_NAME}_CHECKOUT_GIT_SUBMODULES)
if(Git_FOUND)
message(STATUS "Git found, submodule update and init")
execute_process(COMMAND ${GIT_EXECUTABLE} submodule update --init --recursive
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
RESULT_VARIABLE GIT_SUBMOD_RESULT)
if(NOT GIT_SUBMOD_RESULT EQUAL "0")
message(SEND_ERROR "git submodule update --init --recursive failed with ${GIT_SUBMOD_RESULT}, please checkout submodules. This may result in missing dependencies.")
endif()
else()
message(SEND_ERROR "git required for checking out submodules, but not found. Submodules will not be checked out - this may result in missing dependencies.")
endif()
endif()
if(Git_FOUND)
execute_process(
COMMAND git log -1 --format=%h
WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}
OUTPUT_VARIABLE PRJ_GIT_HASH
OUTPUT_STRIP_TRAILING_WHITESPACE
)
else()
message(STATUS "Git not found - the version will not include a git hash.")
set(PRJ_GIT_HASH "unknown")
endif()

View File

@ -0,0 +1,44 @@
# Modified, original version from https://github.com/filipdutescu/modern-cpp-template (Unlicense)
option(${PROJECT_NAME}_WARNINGS_AS_ERRORS "Treat compiler warnings as errors." OFF)
option(${PROJECT_NAME}_CHECKOUT_GIT_SUBMODULES "If git is found, initialize all submodules." ON)
option(${PROJECT_NAME}_ENABLE_UNIT_TESTING "Enable unit tests for the projects (from the `test` subfolder)." ON)
option(${PROJECT_NAME}_ENABLE_CLANG_TIDY "Enable static analysis with Clang-Tidy." OFF)
option(${PROJECT_NAME}_ENABLE_CPPCHECK "Enable static analysis with Cppcheck." OFF)
# TODO Implement code coverage
# option(${PROJECT_NAME}_ENABLE_CODE_COVERAGE "Enable code coverage through GCC." OFF)
option(${PROJECT_NAME}_ENABLE_DOXYGEN "Enable Doxygen documentation builds of source." OFF)
# Generate compile_commands.json for clang based tools
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
# Export all symbols when building a shared library
if(BUILD_SHARED_LIBS)
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS OFF)
set(CMAKE_CXX_VISIBILITY_PRESET hidden)
set(CMAKE_VISIBILITY_INLINES_HIDDEN 1)
endif()
option(${PROJECT_NAME}_ENABLE_LTO "Enable Interprocedural Optimization, aka Link Time Optimization (LTO)." ON)
if(${PROJECT_NAME}_ENABLE_LTO)
include(CheckIPOSupported)
check_ipo_supported(RESULT result OUTPUT output)
if(result)
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE)
else()
message(SEND_ERROR "IPO is not supported: ${output}.")
endif()
endif()
option(${PROJECT_NAME}_ENABLE_CCACHE "Enable the usage of Ccache, in order to speed up rebuild times." ON)
find_program(CCACHE_FOUND ccache)
if(CCACHE_FOUND)
set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE ccache)
set_property(GLOBAL PROPERTY RULE_LAUNCH_LINK ccache)
endif()
option(${PROJECT_NAME}_ENABLE_SANITIZER "Enable sanitizer to detect memory errors, undefined behavior, etc. (slows down the executable)." OFF)
if(${PROJECT_NAME}_ENABLE_SANITIZER)
add_compile_options(-fsanitize=address,undefined)
add_link_options(-fsanitize=address,undefined)
endif()

View File

@ -0,0 +1,20 @@
if(${PROJECT_NAME}_ENABLE_CLANG_TIDY)
find_program(CLANGTIDY clang-tidy)
if(CLANGTIDY)
set(CMAKE_CXX_CLANG_TIDY ${CLANGTIDY} -extra-arg=-Wno-unknown-warning-option)
message("Clang-Tidy finished setting up.")
else()
message(SEND_ERROR "Clang-Tidy requested but executable not found.")
endif()
endif()
if(${PROJECT_NAME}_ENABLE_CPPCHECK)
find_program(CPPCHECK cppcheck)
if(CPPCHECK)
set(CMAKE_CXX_CPPCHECK ${CPPCHECK} --suppress=missingInclude --enable=all
--inline-suppr --inconclusive)
message("Cppcheck finished setting up.")
else()
message(SEND_ERROR "Cppcheck requested but executable not found.")
endif()
endif()

18
cmake/Vcpkg.cmake Normal file
View File

@ -0,0 +1,18 @@
if(NOT CMAKE_TOOLCHAIN_FILE)
if(NOT EXISTS ${CMAKE_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake)
find_package(Git)
if(Git_FOUND)
# shallow-clone vcpkg (we only need the latest revision)
execute_process(COMMAND ${GIT_EXECUTABLE} submodule update --depth=1 --init --recursive vcpkg
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
RESULT_VARIABLE GIT_SUBMOD_RESULT)
if(NOT GIT_SUBMOD_RESULT EQUAL "0")
message(SEND_ERROR "Checking out vcpkg in source tree failed with ${GIT_SUBMOD_RESULT}.")
endif()
else()
message(FATAL_ERROR "Could not find git or vcpkg.cmake. Please either, install git and re-run cmake (or run `git submodule update --init --recursive`), or install vcpkg and add `-DCMAKE_TOOLCHAIN_FILE=<path-to-vcpkg>/scripts/buildsystems/vcpkg.cmake` to your cmake invocation. Please try again after making those changes.")
endif()
endif()
set(CMAKE_TOOLCHAIN_FILE ${CMAKE_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake)
endif()

3
docs/index.md Normal file
View File

@ -0,0 +1,3 @@
# This is the main page of the doxygen generated reference.
You can edit this file under docs/index.md.

57
src/Compression.h Normal file
View File

@ -0,0 +1,57 @@
#pragma once
#include <array>
#include <zlib.h>
#include <algorithm>
#define Biggest 30000
template <typename T>
inline T Comp(const T& Data) {
std::array<char, Biggest> C {};
// obsolete
C.fill(0);
z_stream defstream;
defstream.zalloc = nullptr;
defstream.zfree = nullptr;
defstream.opaque = nullptr;
defstream.avail_in = uInt(Data.size());
defstream.next_in = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(&Data[0]));
defstream.avail_out = Biggest;
defstream.next_out = reinterpret_cast<Bytef*>(C.data());
deflateInit(&defstream, Z_BEST_COMPRESSION);
deflate(&defstream, Z_SYNC_FLUSH);
deflate(&defstream, Z_FINISH);
deflateEnd(&defstream);
size_t TotalOut = defstream.total_out;
T Ret;
Ret.resize(TotalOut);
std::fill(Ret.begin(), Ret.end(), 0);
std::copy_n(C.begin(), TotalOut, Ret.begin());
return Ret;
}
template <typename T>
inline T DeComp(const T& Compressed) {
std::array<char, Biggest> C {};
// not needed
C.fill(0);
z_stream infstream;
infstream.zalloc = nullptr;
infstream.zfree = nullptr;
infstream.opaque = nullptr;
infstream.avail_in = Biggest;
infstream.next_in = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(&Compressed[0]));
infstream.avail_out = Biggest;
infstream.next_out = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(C.data()));
inflateInit(&infstream);
inflate(&infstream, Z_SYNC_FLUSH);
inflate(&infstream, Z_FINISH);
inflateEnd(&infstream);
size_t TotalOut = infstream.total_out;
T Ret;
Ret.resize(TotalOut);
std::fill(Ret.begin(), Ret.end(), 0);
std::copy_n(C.begin(), TotalOut, Ret.begin());
return Ret;
}

41
src/Config.cpp Executable file
View File

@ -0,0 +1,41 @@
#include "Config.h"
#include <boost/iostreams/device/mapped_file.hpp>
#include <filesystem>
#include <fstream>
#include <nlohmann/json.hpp>
Config::Config() {
if (std::filesystem::exists("Launcher.cfg")) {
boost::iostreams::mapped_file cfg("Launcher.cfg", boost::iostreams::mapped_file::mapmode::readonly);
nlohmann::json d = nlohmann::json::parse(cfg.const_data(), nullptr, false);
if (d.is_discarded()) {
is_valid = false;
}
// parse config
if (d["Port"].is_number()) {
port = d["Port"].get<int>();
}
if (d["Build"].is_string()) {
branch = d["Build"].get<std::string>();
for (char& c : branch) {
c = char(tolower(c));
}
}
if (d["GameDir"].is_string()) {
game_dir = d["GameDir"].get<std::string>();
}
} else {
write_to_file();
}
}
void Config::write_to_file() const {
nlohmann::json d {
{ "Port", port },
{ "Branch", branch },
{ "GameDir", game_dir },
};
std::ofstream of("Launcher.cfg", std::ios::trunc);
of << d.dump(4);
}

14
src/Config.h Normal file
View File

@ -0,0 +1,14 @@
#pragma once
#include <filesystem>
struct Config {
Config();
void write_to_file() const;
bool is_valid = true;
int port = 4444;
std::string branch = "Default";
std::string game_dir = "";
};

35
src/Hashing.cpp Normal file
View File

@ -0,0 +1,35 @@
#include "Hashing.h"
#include <boost/iostreams/device/mapped_file.hpp>
#include <cryptopp/hex.h>
#include <cryptopp/sha.h>
#include <cstdio>
#include <filesystem>
#include <fmt/format.h>
#include <errno.h>
std::string sha256_file(const std::string& path) {
CryptoPP::byte digest[CryptoPP::SHA256::DIGESTSIZE];
digest[sizeof(digest) - 1] = 0;
FILE* file = std::fopen(path.c_str(), "rb");
if (!file) {
throw std::runtime_error(fmt::format("Failed to open {}: {}", path, std::strerror(errno)));
}
std::vector<uint8_t> buffer{};
buffer.resize(std::filesystem::file_size(path));
std::fread(buffer.data(), 1, buffer.size(), file);
std::fclose(file);
CryptoPP::SHA256().CalculateDigest(
digest,
buffer.data(), buffer.size());
CryptoPP::HexEncoder encoder;
encoder.Put(digest, sizeof(digest));
encoder.MessageEnd();
std::string encoded {};
if (auto size = encoder.MaxRetrievable(); size != 0)
{
encoded.resize(size);
encoder.Get(reinterpret_cast<CryptoPP::byte*>(&encoded[0]), encoded.size());
}
return encoded;
}

5
src/Hashing.h Normal file
View File

@ -0,0 +1,5 @@
#pragma once
#include <string>
std::string sha256_file(const std::string& path);

115
src/Http.cpp Executable file
View File

@ -0,0 +1,115 @@
#define CPPHTTPLIB_OPENSSL_SUPPORT
#include <iostream>
#include <fstream>
#include <spdlog/spdlog.h>
#include "Http.h"
#include <mutex>
#include <cmath>
#include <httplib.h>
bool HTTP::isDownload = false;
std::string HTTP::Get(const std::string &IP) {
static std::mutex Lock;
std::scoped_lock Guard(Lock);
auto pos = IP.find('/',10);
httplib::Client cli(IP.substr(0, pos).c_str());
cli.set_connection_timeout(std::chrono::seconds(10));
cli.set_follow_location(true);
auto res = cli.Get(IP.substr(pos).c_str(), ProgressBar);
std::string Ret;
if(res){
if(res->status == 200){
Ret = res->body;
}else spdlog::error(res->reason);
}else{
if(isDownload) {
std::cout << "\n";
}
spdlog::error("HTTP Get failed on " + to_string(res.error()));
}
return Ret;
}
std::string HTTP::Post(const std::string& IP, const std::string& Fields) {
static std::mutex Lock;
std::scoped_lock Guard(Lock);
auto pos = IP.find('/',10);
httplib::Client cli(IP.substr(0, pos).c_str());
cli.set_connection_timeout(std::chrono::seconds(10));
std::string Ret;
if(!Fields.empty()) {
httplib::Result res = cli.Post(IP.substr(pos).c_str(), Fields, "application/json");
if(res) {
if (res->status != 200) {
spdlog::error(res->reason);
}
Ret = res->body;
}else{
spdlog::error("HTTP Post failed on " + to_string(res.error()));
}
}else{
httplib::Result res = cli.Post(IP.substr(pos).c_str());
if(res) {
if (res->status != 200) {
spdlog::error(res->reason);
}
Ret = res->body;
}else{
spdlog::error("HTTP Post failed on " + to_string(res.error()));
}
}
if(Ret.empty())return "-1";
else return Ret;
}
bool HTTP::ProgressBar(size_t c, size_t t){
if(isDownload) {
static double last_progress, progress_bar_adv;
progress_bar_adv = round(c / double(t) * 25);
std::cout << "\r";
std::cout << "Progress : [ ";
std::cout << round(c / double(t) * 100);
std::cout << "% ] [";
int i;
for (i = 0; i <= progress_bar_adv; i++)std::cout << "#";
for (i = 0; i < 25 - progress_bar_adv; i++)std::cout << ".";
std::cout << "]";
last_progress = round(c / double(t) * 100);
}
return true;
}
bool HTTP::Download(const std::string &IP, const std::string &Path) {
static std::mutex Lock;
std::scoped_lock Guard(Lock);
isDownload = true;
std::string Ret = Get(IP);
isDownload = false;
if(Ret.empty())return false;
std::ofstream File(Path, std::ios::binary);
if(File.is_open()) {
File << Ret;
File.close();
std::cout << "\n";
spdlog::info("Download Complete!");
}else{
spdlog::error("Failed to open file directory: " + Path);
return false;
}
return true;
}

18
src/Http.h Executable file
View File

@ -0,0 +1,18 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Launcher code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// Created by Anonymous275 on 7/18/2020
///
#pragma once
#include <string>
class HTTP {
public:
static bool Download(const std::string &IP, const std::string &Path);
static std::string Post(const std::string& IP, const std::string& Fields);
static std::string Get(const std::string &IP);
static bool ProgressBar(size_t c, size_t t);
public:
static bool isDownload;
};

114
src/Identity.cpp Normal file
View File

@ -0,0 +1,114 @@
#include "Identity.h"
#include "Http.h"
#include <filesystem>
#include <fstream>
#include <nlohmann/json.hpp>
#include <spdlog/spdlog.h>
namespace fs = std::filesystem;
Identity::Identity() {
check_local_key();
}
void Identity::check_local_key() {
if (fs::exists("key") && fs::file_size("key") < 100) {
std::ifstream Key("key");
if (Key.is_open()) {
auto Size = fs::file_size("key");
std::string Buffer(Size, 0);
Key.read(&Buffer[0], static_cast<long>(Size));
Key.close();
for (char& c : Buffer) {
if (!std::isalnum(c) && c != '-') {
update_key(nullptr);
return;
}
}
Buffer = HTTP::Post("https://auth.beammp.com/userlogin", R"({"pk":")" + Buffer + "\"}");
nlohmann::json d = nlohmann::json::parse(Buffer, nullptr, false);
if (Buffer == "-1" || Buffer.at(0) != '{' || d.is_discarded()) {
spdlog::error(Buffer);
spdlog::info("Invalid answer from authentication servers.");
update_key(nullptr);
}
if (d["success"].get<bool>()) {
LoginAuth = true;
spdlog::info("{}", d["message"].get<std::string>());
update_key(d["private_key"].get<std::string>().c_str());
PublicKey = d["public_key"].get<std::string>();
Role = d["role"].get<std::string>();
} else {
spdlog::info("Auto-Authentication unsuccessful please re-login!");
update_key(nullptr);
}
} else {
spdlog::warn("Could not open saved key!");
update_key(nullptr);
}
} else
update_key(nullptr);
}
void Identity::update_key(const char* newKey) {
if (newKey && std::isalnum(newKey[0])) {
PrivateKey = newKey;
std::ofstream Key("key");
if (Key.is_open()) {
Key << newKey;
Key.close();
} else {
spdlog::error("Cannot write key to disk!");
}
} else if (fs::exists("key")) {
fs::remove("key");
}
}
static std::string GetFail(const std::string& R) {
std::string DRet = R"({"success":false,"message":)";
DRet += "\"" + R + "\"}";
spdlog::error(R);
return DRet;
}
std::string Identity::login(const std::string& fields) {
spdlog::debug("Logging in with {}", fields);
if (fields == "LO") {
LoginAuth = false;
update_key(nullptr);
return "";
}
spdlog::info("Attempting to authenticate...");
std::string Buffer = HTTP::Post("https://auth.beammp.com/userlogin", fields);
if (Buffer == "-1") {
return GetFail("Failed to communicate with the auth system!");
}
nlohmann::json d = nlohmann::json::parse(Buffer, nullptr, false);
if (Buffer.at(0) != '{' || d.is_discarded()) {
spdlog::error(Buffer);
return GetFail("Invalid answer from authentication servers, please try again later!");
}
if (d.contains("success") && d["success"].get<bool>()) {
LoginAuth = true;
if (d.contains("private_key")) {
update_key(d["private_key"].get<std::string>().c_str());
}
if (d.contains("public_key")) {
PublicKey = d["public_key"].get<std::string>();
}
spdlog::info("Authentication successful!");
} else {
spdlog::info("Authentication failed!");
}
d.erase("private_key");
d.erase("public_key");
return d.dump();
}

18
src/Identity.h Normal file
View File

@ -0,0 +1,18 @@
#pragma once
#include <string>
struct Identity {
Identity();
void check_local_key();
bool LoginAuth { false };
std::string PublicKey;
std::string PrivateKey;
std::string Role;
std::string login(const std::string& fields);
private:
void update_key(const char* newKey);
};

888
src/Launcher.cpp Normal file
View File

@ -0,0 +1,888 @@
#include "Launcher.h"
#include "Compression.h"
#include "Hashing.h"
#include "Http.h"
#include "Platform.h"
#include "Version.h"
#include <boost/asio.hpp>
#include <boost/iostreams/device/mapped_file.hpp>
#include <boost/process.hpp>
#include <chrono>
#include <filesystem>
#include <fmt/format.h>
#include <httplib.h>
#include <limits>
#include <nlohmann/json.hpp>
#include <spdlog/spdlog.h>
#include <vector>
using namespace boost::asio;
namespace fs = std::filesystem;
Launcher::Launcher()
: m_game_socket(m_io)
, m_core_socket(m_io)
, m_tcp_socket(m_io)
, m_udp_socket(m_io) {
spdlog::debug("Launcher startup");
m_config = Config {};
if (!m_config->is_valid) {
spdlog::error("Launcher config invalid!");
}
}
/// Sets shared headers for all backend proxy messages
static void proxy_set_headers(httplib::Response& res) {
res.set_header("Access-Control-Allow-Origin", "*");
res.set_header("Access-Control-Request-Method", "POST, OPTIONS, GET");
res.set_header("Access-Control-Request-Headers", "X-API-Version");
}
void Launcher::proxy_main() {
httplib::Server HTTPProxy;
httplib::Headers headers = {
{ "User-Agent", fmt::format("BeamMP-Launcher/{}.{}.{}", PRJ_VERSION_MAJOR, PRJ_VERSION_MINOR, PRJ_VERSION_PATCH) },
{ "Accept", "*/*" }
};
std::string pattern = "/:any1";
for (int i = 2; i <= 4; i++) {
HTTPProxy.Get(pattern, [&](const httplib::Request& req, httplib::Response& res) {
httplib::Client cli("https://backend.beammp.com");
proxy_set_headers(res);
if (req.has_header("X-BMP-Authentication")) {
headers.emplace("X-BMP-Authentication", m_identity->PrivateKey);
}
if (req.has_header("X-API-Version")) {
headers.emplace("X-API-Version", req.get_header_value("X-API-Version"));
}
if (auto cli_res = cli.Get(req.path, headers); cli_res) {
res.set_content(cli_res->body, cli_res->get_header_value("Content-Type"));
} else {
res.set_content(to_string(cli_res.error()), "text/plain");
}
});
HTTPProxy.Post(pattern, [&](const httplib::Request& req, httplib::Response& res) {
httplib::Client cli("https://backend.beammp.com");
proxy_set_headers(res);
if (req.has_header("X-BMP-Authentication")) {
headers.emplace("X-BMP-Authentication", m_identity->PrivateKey);
}
if (req.has_header("X-API-Version")) {
headers.emplace("X-API-Version", req.get_header_value("X-API-Version"));
}
if (auto cli_res = cli.Post(req.path, headers, req.body,
req.get_header_value("Content-Type"));
cli_res) {
res.set_content(cli_res->body, cli_res->get_header_value("Content-Type"));
} else {
res.set_content(to_string(cli_res.error()), "text/plain");
}
});
pattern += "/:any" + std::to_string(i);
}
m_proxy_port = HTTPProxy.bind_to_any_port("0.0.0.0");
spdlog::debug("http proxy started on port {}", m_proxy_port.get());
HTTPProxy.listen_after_bind();
}
Launcher::~Launcher() {
m_proxy_thread.interrupt();
m_game_thread.detach();
}
void Launcher::parse_config() {
}
void Launcher::set_port(int p) {
spdlog::warn("Using custom port {}", p);
m_config->port = p;
}
void Launcher::check_for_updates(int argc, char** argv) {
std::string LatestHash = HTTP::Get(fmt::format("https://backend.beammp.com/sha/launcher?branch={}&pk={}", m_config->branch, m_identity->PublicKey));
std::string LatestVersion = HTTP::Get(fmt::format("https://backend.beammp.com/version/launcher?branch={}&pk={}", m_config->branch, m_identity->PublicKey));
std::string DownloadURL = fmt::format("https://backend.beammp.com/builds/launcher?download=true"
"&pk={}"
"&branch={}",
m_identity->PublicKey, m_config->branch);
spdlog::debug("Latest hash: {}", LatestHash);
spdlog::debug("Latest version: {}", LatestVersion);
transform(LatestHash.begin(), LatestHash.end(), LatestHash.begin(), ::tolower);
std::string EP = (m_exe_path.get() / m_exe_name.get()).generic_string();
std::string Back = m_exe_path.get() / "BeamMP-Launcher.back";
std::string FileHash = sha256_file(EP);
if (FileHash != LatestHash
&& Version(PRJ_VERSION_MAJOR, PRJ_VERSION_MINOR, PRJ_VERSION_PATCH).is_outdated(Version(LatestVersion))) {
spdlog::info("Launcher update found!");
fs::remove(Back);
fs::rename(EP, Back);
spdlog::info("Downloading Launcher update " + LatestHash);
HTTP::Download(DownloadURL, EP);
plat::URelaunch(argc, argv);
} else {
spdlog::info("Launcher version is up to date");
}
}
void Launcher::find_game() {
// try to find the game by multiple means
spdlog::info("Locating game");
// 0. config!
if (!m_config->game_dir.empty()
&& std::filesystem::exists(std::filesystem::path(m_config->game_dir) / "BeamNG.drive.exe")) {
spdlog::debug("Found game directory in config: '{}'", m_config->game_dir);
return;
}
// 1. magic
auto game_dir = plat::get_game_dir_magically();
if (!game_dir.empty()) {
m_config->game_dir = game_dir;
m_config->write_to_file();
return;
} else {
spdlog::debug("Couldn't magically find game directory");
}
// 2. ask
m_config->game_dir = plat::ask_for_folder();
spdlog::debug("Located game at '{}'", m_config->game_dir);
m_config->write_to_file();
}
static std::string check_game_version(const std::filesystem::path& dir) {
std::string temp;
std::string Path = (dir / "integrity.json").generic_string();
boost::iostreams::mapped_file file(Path);
auto json = nlohmann::json::parse(file.const_begin(), file.const_end());
return json["version"].is_string() ? json["version"].get<std::string>() : "";
}
void Launcher::pre_game() {
std::string GameVer = check_game_version(m_config->game_dir);
if (GameVer.empty()) {
spdlog::error("Game version is empty!");
}
spdlog::info("Game Version: " + GameVer);
check_mp((std::filesystem::path(m_config->game_dir) / "mods/multiplayer").generic_string());
std::string LatestHash = HTTP::Get(fmt::format("https://backend.beammp.com/sha/mod?branch={}&pk={}", m_config->branch, m_identity->PublicKey));
transform(LatestHash.begin(), LatestHash.end(), LatestHash.begin(), ::tolower);
LatestHash.erase(std::remove_if(LatestHash.begin(), LatestHash.end(),
[](auto const& c) -> bool { return !std::isalnum(c); }),
LatestHash.end());
try {
if (!fs::exists(std::filesystem::path(m_config->game_dir) / "mods/multiplayer")) {
fs::create_directories(std::filesystem::path(m_config->game_dir) / "mods/multiplayer");
}
enable_mp();
} catch (std::exception& e) {
spdlog::error("Fatal: {}", e.what());
std::exit(1);
}
auto ZipPath(std::filesystem::path(m_config->game_dir) / "mods/multiplayer/BeamMP.zip");
std::string FileHash = sha256_file(ZipPath);
if (FileHash != LatestHash) {
spdlog::info("Downloading BeamMP Update " + LatestHash);
HTTP::Download(fmt::format("https://backend.beammp.com/builds/client?download=true&pk={}&branch={}", m_identity->PublicKey, m_config->branch), ZipPath);
}
auto Target = std::filesystem::path(m_config->game_dir) / "mods/unpacked/beammp";
if (fs::is_directory(Target)) {
fs::remove_all(Target);
}
}
static size_t count_items_in_dir(const std::filesystem::path& path) {
return static_cast<size_t>(std::distance(std::filesystem::directory_iterator { path }, std::filesystem::directory_iterator {}));
}
void Launcher::check_mp(const std::string& path) {
if (!fs::exists(path))
return;
size_t c = count_items_in_dir(fs::path(path));
try {
for (auto& p : fs::directory_iterator(path)) {
if (p.exists() && !p.is_directory()) {
std::string name = p.path().filename().string();
for (char& Ch : name)
Ch = char(tolower(Ch));
if (name != "beammp.zip")
fs::remove(p.path());
}
}
} catch (...) {
spdlog::error("We were unable to clean the multiplayer mods folder! Is the game still running or do you have something open in that folder?");
std::this_thread::sleep_for(std::chrono::seconds(5));
std::exit(1);
}
}
void Launcher::enable_mp() {
std::string File = (std::filesystem::path(m_config->game_dir) / "mods/db.json").generic_string();
if (!fs::exists(File))
return;
auto Size = fs::file_size(File);
if (Size < 2)
return;
std::ifstream db(File);
if (db.is_open()) {
std::string Data(Size, 0);
db.read(&Data[0], Size);
db.close();
nlohmann::json d = nlohmann::json::parse(Data, nullptr, false);
if (Data.at(0) != '{' || d.is_discarded()) {
// spdlog::error("Failed to parse " + File); //TODO illegal formatting
return;
}
if (d.contains("mods") && d["mods"].contains("multiplayerbeammp")) {
d["mods"]["multiplayerbeammp"]["active"] = true;
std::ofstream ofs(File);
if (ofs.is_open()) {
ofs << d.dump();
ofs.close();
} else {
spdlog::error("Failed to write " + File);
}
}
}
}
void Launcher::game_main() {
auto path = std::filesystem::current_path();
std::filesystem::current_path(m_config->game_dir);
#if defined(PLATFORM_LINUX)
auto game_path = (std::filesystem::path(m_config->game_dir) / "BinLinux/BeamNG.drive.x64").generic_string();
#elif defined(PLATFORM_WINDOWS)
auto game_path = (m_game_dir.get() / "Bin64/BeamNG.drive.x64.exe").generic_string();
#endif
boost::process::child game(game_path, boost::process::std_out > boost::process::null);
std::filesystem::current_path(path);
if (game.running()) {
spdlog::info("Game launched!");
game.wait();
spdlog::info("Game closed! Launcher closing soon");
} else {
spdlog::error("Failed to launch the game! Please start the game manually.");
}
}
void Launcher::start_game() {
m_game_thread = boost::scoped_thread<>(&Launcher::game_main, this);
}
void Launcher::start_network() {
while (true) {
try {
net_core_main();
} catch (const std::exception& e) {
spdlog::error("Error: {}", e.what());
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
void Launcher::reset_status() {
*m_m_status = " ";
*m_ul_status = "Ulstart";
m_conf_list->clear();
*m_ping = -1;
}
void Launcher::net_core_main() {
ip::tcp::endpoint listen_ep(ip::address::from_string("0.0.0.0"), static_cast<uint16_t>(m_config->port));
ip::tcp::socket listener(m_io);
boost::system::error_code ec;
listener.open(listen_ep.protocol(), ec);
if (ec) {
spdlog::error("Failed to open socket: {}", ec.message());
return;
}
socket_base::linger linger_opt {};
linger_opt.enabled(false);
listener.set_option(linger_opt, ec);
if (ec) {
spdlog::error("Failed to set up listening socket to not linger / reuse address. "
"This may cause the socket to refuse to bind(). spdlog::error: {}",
ec.message());
}
ip::tcp::acceptor acceptor(m_io, listen_ep);
acceptor.listen(socket_base::max_listen_connections, ec);
if (ec) {
spdlog::error("listen() failed, which is needed for the launcher to operate. "
"Shutting down. spdlog::error: {}",
ec.message());
std::this_thread::sleep_for(std::chrono::seconds(3));
std::exit(1);
}
do {
try {
spdlog::info("Waiting for the game to connect");
ip::tcp::endpoint game_ep;
m_game_socket = acceptor.accept(game_ep, ec);
if (ec) {
spdlog::error("Failed to accept: {}", ec.message());
}
reset_status();
spdlog::info("Game connected!");
spdlog::debug("Game: [{}]:{}", game_ep.address().to_string(), game_ep.port());
game_loop();
spdlog::warn("Game disconnected!");
} catch (const std::exception& e) {
spdlog::error("Fatal error in core network: {}", e.what());
}
} while (!*m_shutdown);
}
void Launcher::game_loop() {
size_t Size;
size_t Temp;
size_t Rcv;
char Header[10] = { 0 };
boost::system::error_code ec;
do {
Rcv = 0;
do {
Temp = boost::asio::read(m_game_socket, buffer(&Header[Rcv], 1), ec);
if (ec) {
spdlog::error("(Core) Failed to receive from game: {}", ec.message());
break;
}
if (Temp < 1)
break;
if (!isdigit(Header[Rcv]) && Header[Rcv] != '>') {
spdlog::error("(Core) Invalid lua communication: '{}'", std::string(Header, Rcv));
break;
}
} while (Header[Rcv++] != '>');
if (Temp < 1)
break;
if (std::from_chars(Header, &Header[Rcv], Size).ptr[0] != '>') {
spdlog::debug("(Core) Invalid lua Header: '{}'", std::string(Header, Rcv));
break;
}
std::vector<char> Ret(Size, 0);
Rcv = 0;
Temp = boost::asio::read(m_game_socket, buffer(Ret, Size), ec);
if (ec) {
spdlog::error("(Core) Failed to receive from game: {}", ec.message());
break;
}
handle_core_packet(Ret);
} while (Temp > 0);
if (Temp == 0) {
spdlog::debug("(Core) Connection closing");
}
// TODO: NetReset
}
static bool IsAllowedLink(const std::string& Link) {
std::regex link_pattern(R"(https:\/\/(?:\w+)?(?:\.)?(?:beammp\.com|discord\.gg))");
std::smatch link_match;
return std::regex_search(Link, link_match, link_pattern) && link_match.position() == 0;
}
void Launcher::handle_core_packet(const std::vector<char>& RawData) {
std::string Data(RawData.begin(), RawData.end());
char Code = Data.at(0), SubCode = 0;
if (Data.length() > 1)
SubCode = Data.at(1);
switch (Code) {
case 'A':
Data = Data.substr(0, 1);
break;
case 'B':
Data = Code + HTTP::Get("https://backend.beammp.com/servers-info");
break;
case 'C':
m_list_of_mods->clear();
if (!start_sync(Data)) {
// TODO: Handle
spdlog::error("start_sync failed, spdlog::error case not implemented");
}
while (m_list_of_mods->empty() && !*m_shutdown) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
if (m_list_of_mods.get() == "-")
Data = "L";
else
Data = "L" + m_list_of_mods.get();
break;
case 'O': // open default browser with URL
if (IsAllowedLink(Data.substr(1))) {
spdlog::info("Opening Link \"" + Data.substr(1) + "\"");
boost::process::child c(std::string("open '") + Data.substr(1) + "'", boost::process::std_out > boost::process::null);
c.detach();
}
Data.clear();
break;
case 'P':
Data = Code + std::to_string(*m_proxy_port);
break;
case 'U':
if (SubCode == 'l')
Data = *m_ul_status;
if (SubCode == 'p') {
if (*m_ping > 800) {
Data = "Up-2";
} else
Data = "Up" + std::to_string(*m_ping);
}
if (!SubCode) {
std::string Ping;
if (*m_ping > 800)
Ping = "-2";
else
Ping = std::to_string(*m_ping);
Data = std::string(*m_ul_status) + "\n" + "Up" + Ping;
}
break;
case 'M':
Data = *m_m_status;
break;
case 'Q':
if (SubCode == 'S') {
spdlog::debug("Shutting down via QS");
*m_shutdown = true;
*m_ping = -1;
}
if (SubCode == 'G') {
spdlog::debug("Shutting down via QG");
*m_shutdown = true;
}
Data.clear();
break;
case 'R': // will send mod name
if (m_conf_list->find(Data) == m_conf_list->end()) {
m_conf_list->insert(Data);
m_mod_loaded = true;
}
Data.clear();
break;
case 'Z':
Data = fmt::format("Z{}.{}", PRJ_VERSION_MAJOR, PRJ_VERSION_MINOR);
break;
case 'N':
if (SubCode == 'c') {
Data = "N{\"Auth\":" + std::to_string(m_identity->LoginAuth) + "}";
} else {
Data = "N" + m_identity->login(Data.substr(Data.find(':') + 1));
}
break;
default:
Data.clear();
break;
}
if (!Data.empty() && m_game_socket.is_open()) {
boost::system::error_code ec;
boost::asio::write(m_game_socket, buffer((Data + "\n").c_str(), Data.size() + 1), ec);
if (ec) {
spdlog::error("(Core) send failed with error: {}", ec.message());
}
}
}
static void compress_properly(std::vector<uint8_t>& Data) {
constexpr std::string_view ABG = "ABG:";
auto CombinedData = std::vector<uint8_t>(ABG.begin(), ABG.end());
auto CompData = Comp(Data);
CombinedData.resize(ABG.size() + CompData.size());
std::copy(CompData.begin(), CompData.end(), CombinedData.begin() + ABG.size());
Data = CombinedData;
}
void Launcher::send_large(const std::string& Data) {
std::vector<uint8_t> vec(Data.data(), Data.data() + Data.size());
compress_properly(vec);
tcp_send(vec);
}
void Launcher::server_send(const std::string& Data, bool Rel) {
if (Data.empty())
return;
if (Data.find("Zp") != std::string::npos && Data.size() > 500) {
abort();
}
char C = 0;
bool Ack = false;
int DLen = int(Data.length());
if (DLen > 3) {
C = Data.at(0);
}
if (C == 'O' || C == 'T') {
Ack = true;
}
if (C == 'N' || C == 'W' || C == 'Y' || C == 'V' || C == 'E' || C == 'C') {
Rel = true;
}
if (Ack || Rel) {
if (Ack || DLen > 1000) {
send_large(Data);
} else {
tcp_send(Data);
}
} else {
udp_send(Data);
}
if (DLen > 1000) {
spdlog::debug("(Launcher->Server) Bytes sent: " + std::to_string(Data.length()) + " : "
+ Data.substr(0, 10)
+ Data.substr(Data.length() - 10));
} else if (C == 'Z') {
// spdlog::debug("(Game->Launcher) : " + Data);
}
}
void Launcher::tcp_game_main() {
spdlog::debug("Game server starting on port {}", m_config->port + 1);
ip::tcp::endpoint listen_ep(ip::address::from_string("0.0.0.0"), static_cast<uint16_t>(m_config->port + 1));
ip::tcp::socket g_listener(m_io);
g_listener.open(listen_ep.protocol());
socket_base::linger linger_opt {};
linger_opt.enabled(false);
g_listener.set_option(linger_opt);
ip::tcp::acceptor g_acceptor(m_io, listen_ep);
g_acceptor.listen(socket_base::max_listen_connections);
spdlog::debug("Game server listening");
while (!*m_shutdown) {
spdlog::debug("Main loop");
// socket is connected at this point, spawn thread
m_client_thread = boost::scoped_thread<>(&Launcher::tcp_client_main, this);
spdlog::debug("Client thread spawned");
m_core_socket = g_acceptor.accept();
spdlog::debug("Game connected (tcp game)!");
spdlog::info("Successfully connected");
m_ping_thread = boost::scoped_thread<>(&Launcher::auto_ping, this);
m_udp_thread = boost::scoped_thread<>(&Launcher::udp_main, this);
int32_t Temp = 0;
do {
boost::system::error_code ec;
int32_t Rcv = 0;
int32_t Size = 0;
char Header[10] = { 0 };
do {
Temp = boost::asio::read(m_core_socket, buffer(&Header[Rcv], 1), ec);
if (ec) {
spdlog::error("(Game) Failed to receive from game: {}", ec.message());
break;
}
if (Temp < 1)
break;
if (!isdigit(Header[Rcv]) && Header[Rcv] != '>') {
spdlog::error("(Game) Invalid lua communication");
break;
}
} while (Header[Rcv++] != '>');
if (Temp < 1)
break;
if (std::from_chars(Header, &Header[Rcv], Size).ptr[0] != '>') {
spdlog::debug("(Game) Invalid lua Header -> " + std::string(Header, Rcv));
break;
}
std::vector<char> Ret(Size, 0);
Rcv = 0;
Temp = boost::asio::read(m_core_socket, buffer(Ret, Size), ec);
if (ec) {
spdlog::error("(Game) Failed to receive from game: {}", ec.message());
break;
}
spdlog::debug("Got {} from the game, sending to server", Ret[0]);
server_send(std::string(Ret.begin(), Ret.end()), false);
} while (Temp > 0);
if (Temp == 0) {
spdlog::debug("(Proxy) Connection closing");
} else {
spdlog::debug("(Proxy) Recv failed");
}
}
spdlog::debug("Game server exiting");
}
bool Launcher::start_sync(const std::string& Data) {
ip::tcp::resolver resolver(m_io);
const auto sep = Data.find_last_of(':');
if (sep == std::string::npos || sep == Data.length() - 1) {
spdlog::error("Invalid host:port string: '{}'", Data);
return false;
}
const auto host = Data.substr(1, sep - 1);
const auto service = Data.substr(sep + 1);
boost::system::error_code ec;
auto resolved = resolver.resolve(host, service, ec);
if (ec) {
spdlog::error("Failed to resolve '{}': {}", Data.substr(1), ec.message());
return false;
}
bool connected = false;
for (const auto& addr : resolved) {
m_tcp_socket.connect(addr.endpoint(), ec);
if (!ec) {
spdlog::info("Resolved and connected to '[{}]:{}'",
addr.endpoint().address().to_string(),
addr.endpoint().port());
connected = true;
if (addr.endpoint().address().is_v4()) {
m_udp_socket.open(ip::udp::v4());
} else {
m_udp_socket.open(ip::udp::v6());
}
m_udp_endpoint = ip::udp::endpoint(m_tcp_socket.remote_endpoint().address(), m_tcp_socket.remote_endpoint().port());
break;
}
}
if (!connected) {
spdlog::error("Failed to connect to '{}'", Data);
return false;
}
reset_status();
m_identity->check_local_key();
*m_ul_status = "UlLoading...";
auto thread = boost::scoped_thread<>(&Launcher::tcp_game_main, this);
m_tcp_game_thread.swap(thread);
return true;
}
void Launcher::tcp_send(const std::vector<uint8_t>& data) {
const auto Size = int32_t(data.size());
std::vector<uint8_t> ToSend;
ToSend.resize(data.size() + sizeof(Size));
std::memcpy(ToSend.data(), &Size, sizeof(Size));
std::memcpy(ToSend.data() + sizeof(Size), data.data(), data.size());
boost::system::error_code ec;
spdlog::debug("tcp sending {} bytes to the server", data.size());
boost::asio::write(m_tcp_socket, buffer(ToSend), ec);
if (ec) {
spdlog::debug("write(): {}", ec.message());
throw std::runtime_error(fmt::format("write() failed: {}", ec.message()));
}
spdlog::debug("tcp sent {} bytes to the server", data.size());
}
void Launcher::tcp_send(const std::string& data) {
tcp_send(std::vector<uint8_t>(data.begin(), data.end()));
}
std::string Launcher::tcp_recv() {
int32_t Header {};
boost::system::error_code ec;
std::array<uint8_t, sizeof(Header)> HeaderData {};
boost::asio::read(m_tcp_socket, buffer(HeaderData), ec);
if (ec) {
throw std::runtime_error(fmt::format("read() failed: {}", ec.message()));
}
Header = *reinterpret_cast<int32_t*>(HeaderData.data());
if (Header < 0) {
throw std::runtime_error("read() failed: Negative TCP header");
}
std::vector<uint8_t> Data;
// 100 MiB is super arbitrary but what can you do.
if (Header < int32_t(100 * (1024 * 1024))) {
Data.resize(Header);
} else {
throw std::runtime_error("Header size limit exceeded");
}
auto N = boost::asio::read(m_tcp_socket, buffer(Data), ec);
if (ec) {
throw std::runtime_error(fmt::format("read() failed: {}", ec.message()));
}
if (N != Header) {
throw std::runtime_error(fmt::format("read() failed: Expected {} byte(s), got {} byte(s) instead", Header, N));
}
constexpr std::string_view ABG = "ABG:";
if (Data.size() >= ABG.size() && std::equal(Data.begin(), Data.begin() + ABG.size(), ABG.begin(), ABG.end())) {
Data.erase(Data.begin(), Data.begin() + ABG.size());
Data = DeComp(Data);
}
return { reinterpret_cast<const char*>(Data.data()), Data.size() };
}
void Launcher::game_send(const std::string& data) {
auto to_send = data + "\n";
boost::asio::write(m_core_socket, buffer(reinterpret_cast<const uint8_t*>(to_send.data()), to_send.size()));
}
void Launcher::tcp_client_main() {
spdlog::debug("Client starting");
boost::system::error_code ec;
try {
{
// send C to say hi
boost::asio::write(m_tcp_socket, buffer("C", 1), ec);
// client version
tcp_send(fmt::format("VC{}.{}", PRJ_VERSION_MAJOR, PRJ_VERSION_MINOR));
// auth
auto res = tcp_recv();
if (res.empty() || res[0] == 'E') {
throw std::runtime_error("Kicked!");
} else if (res[0] == 'K') {
if (res.size() > 1) {
throw std::runtime_error(fmt::format("Kicked: {}", res.substr(1)));
} else {
throw std::runtime_error("Kicked!");
}
}
tcp_send(m_identity->PublicKey);
res = tcp_recv();
if (res.empty() || res[0] != 'P') {
throw std::runtime_error("Expected 'P'");
}
if (res.size() > 1 && std::all_of(res.begin() + 1, res.end(), [](char c) { return std::isdigit(c); })) {
*m_client_id = std::stoi(res.substr(1));
} else {
// auth failed
throw std::runtime_error("Authentication failed");
}
tcp_send("SR");
res = tcp_recv();
if (res.empty() || res[0] == 'E') {
throw std::runtime_error("Kicked!");
} else if (res[0] == 'K') {
if (res.size() > 1) {
throw std::runtime_error(fmt::format("Kicked: {}", res.substr(1)));
} else {
throw std::runtime_error("Kicked!");
}
}
if (res == "-") {
spdlog::info("Didn't receive any mods");
*m_list_of_mods = "-";
tcp_send("Done");
spdlog::info("Done!");
}
// auth done!
}
if (m_list_of_mods.get() != "-") {
spdlog::info("Checking resources");
if (!std::filesystem::exists("Resources")) {
std::filesystem::create_directories("Resources");
}
throw std::runtime_error("Mod loading not yet implemented");
}
std::string res;
while (!*m_shutdown) {
res = tcp_recv();
server_parse(res);
}
game_send("T");
} catch (const std::exception& e) {
spdlog::error("Fatal error: {}", e.what());
*m_shutdown = true;
}
spdlog::debug("Client stopping");
}
void Launcher::server_parse(const std::string& data) {
if (data.empty()) {
return;
}
switch (data[0]) {
case 'p':
*m_ping_end = std::chrono::high_resolution_clock::now();
if (m_ping_start.get() > m_ping_end.get()) {
*m_ping = 0;
} else {
*m_ping = int(std::chrono::duration_cast<std::chrono::milliseconds>(m_ping_end.get() - m_ping_start.get()).count());
}
break;
case 'M':
*m_m_status = data;
*m_ul_status = "Uldone";
break;
default:
game_send(data);
}
}
std::string Launcher::udp_recv() {
// the theoretical maximum udp message is 64 KiB, so we save one buffer per thread for it
static thread_local std::vector<char> s_local_buf(size_t(64u * 1024u));
auto n = m_udp_socket.receive_from(buffer(s_local_buf), m_udp_endpoint);
return { s_local_buf.data(), n };
}
void Launcher::udp_main() {
spdlog::info("UDP starting");
try {
game_send(std::string("P") + std::to_string(*m_client_id));
tcp_send("H");
udp_send("p");
while (!*m_shutdown) {
auto msg = udp_recv();
if (!msg.empty() && msg.length() > 4 && msg.substr(0, 4) == "ABG:") {
server_parse(std::string(DeComp(msg)));
} else {
server_parse(std::string(msg));
}
}
} catch (const std::exception& e) {
spdlog::error("Error in udp_main: {}", e.what());
}
spdlog::info("UDP stopping");
}
void Launcher::auto_ping() {
spdlog::debug("Ping thread started");
while (!*m_shutdown) {
udp_send("p");
*m_ping_start = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
spdlog::debug("Ping thread stopped");
}
void Launcher::udp_send(const std::string& data) {
auto vec = std::vector<uint8_t>(data.begin(), data.end());
if (data.length() > 400) {
compress_properly(vec);
}
std::vector<uint8_t> to_send = { uint8_t(*m_client_id), uint8_t(':') };
to_send.insert(to_send.end(), vec.begin(), vec.end());
m_udp_socket.send_to(buffer(to_send.data(), to_send.size()), m_udp_endpoint);
}

113
src/Launcher.h Normal file
View File

@ -0,0 +1,113 @@
#pragma once
#include "Config.h"
#include "Identity.h"
#include "Sync.h"
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ip/udp.hpp>
#include <boost/thread/scoped_thread.hpp>
#include <filesystem>
#include <set>
#include <string>
#include <thread>
class Launcher {
public:
Launcher();
~Launcher();
void set_port(int p);
void check_for_updates(int argc, char** argv);
void set_exe_name(const std::string& name) { m_exe_name = name; }
void set_exe_path(const std::filesystem::path& path) { m_exe_path = path; }
void find_game();
void pre_game();
void start_game();
void start_network();
private:
/// Thread main function for the http(s) proxy thread.
void proxy_main();
/// Thread main function for the game thread.
void game_main();
/// Thread main function for the clien thread (the one that talks to the server)
void tcp_client_main();
void tcp_game_main();
void udp_main();
void auto_ping();
void parse_config();
static void check_mp(const std::string& path);
void enable_mp();
void net_core_main();
void reset_status();
void game_loop();
void handle_core_packet(const std::vector<char>& RawData);
bool start_sync(const std::string& Data);
void server_parse(const std::string& data);
void udp_send(const std::string& data);
void server_send(const std::string& data, bool Res);
void tcp_send(const std::string& data);
void send_large(const std::string& data);
void tcp_send(const std::vector<uint8_t>& data);
std::string tcp_recv();
std::string udp_recv();
void game_send(const std::string& data);
Sync<int> m_proxy_port;
Sync<int> m_ping;
Sync<int> m_client_id;
Sync<bool> m_mod_loaded { false };
Sync<Config> m_config;
boost::scoped_thread<> m_proxy_thread { &Launcher::proxy_main, this };
boost::scoped_thread<> m_game_thread;
boost::scoped_thread<> m_client_thread;
boost::scoped_thread<> m_tcp_game_thread;
boost::scoped_thread<> m_udp_thread;
boost::scoped_thread<> m_ping_thread;
Sync<Identity> m_identity {};
Sync<std::string> m_exe_name;
Sync<std::filesystem::path> m_exe_path;
boost::asio::io_context m_io {};
boost::asio::ip::tcp::socket m_game_socket;
boost::asio::ip::tcp::socket m_core_socket;
boost::asio::ip::tcp::socket m_tcp_socket;
boost::asio::ip::udp::socket m_udp_socket;
boost::asio::ip::udp::endpoint m_udp_endpoint;
Sync<bool> m_shutdown { false };
Sync<std::chrono::high_resolution_clock::time_point> m_ping_start;
Sync<std::chrono::high_resolution_clock::time_point> m_ping_end;
Sync<std::string> m_m_status {};
Sync<std::string> m_ul_status {};
Sync<std::set<std::string>> m_conf_list;
Sync<std::string> m_list_of_mods {};
};

14
src/Platform.h Normal file
View File

@ -0,0 +1,14 @@
#pragma once
/// Platform-specific code
#include <string>
namespace plat {
void clear_screen();
void set_console_title(const std::string& title);
void URelaunch(int argc,char* args[]);
void ReLaunch(int argc,char*args[]);
std::string get_game_dir_magically();
std::string ask_for_folder();
}

49
src/PlatformLinux.cpp Normal file
View File

@ -0,0 +1,49 @@
#include "Platform.h"
#if defined(PLATFORM_LINUX)
#include <fmt/core.h>
#include <spdlog/spdlog.h>
#include <filesystem>
void plat::ReLaunch(int argc, char* args[]) {
spdlog::warn("Not implemented: {}", __func__);
}
void plat::URelaunch(int argc, char** argv) {
spdlog::warn("Not implemented: {}", __func__);
}
void plat::set_console_title(const std::string& title) {
//fmt::print("\x1b]2;{}\0", title);
}
void plat::clear_screen() {
// unwanted on linux, due to the ability to run this as a command in an existing console.
}
std::string plat::get_game_dir_magically() {
spdlog::warn("Not implemented: {}", __func__);
for (const auto& path : { "" }) {
if (std::filesystem::exists(std::filesystem::path(path) / "BeamNG.drive.exe")) {
return path;
}
}
return "";
}
#include <iostream>
#include <filesystem>
std::string plat::ask_for_folder() {
spdlog::info("Asking user for path");
fmt::print("====\n"
"Couldn't find game directory, please enter the path to the game (the folder that contains 'BeamNG.drive.exe')\n"
"Path: ");
std::string folder;
std::getline(std::cin, folder);
while (!std::filesystem::exists(std::filesystem::path(folder) / "BeamNG.drive.exe")) {
fmt::print("This folder ('{}') doesn't contain 'BeamNG.drive.exe', please try again.\n", folder);
fmt::print("Path: ");
std::getline(std::cin, folder);
}
fmt::print("Thank you!\n====\n");
spdlog::info("Game path found");
return folder;
}
#endif

177
src/PlatformWindows.cpp Normal file
View File

@ -0,0 +1,177 @@
#include "Platform.h"
#if defined(PLATFORM_WINDOWS)
#include <spdlog/spdlog.h>
#include <windows.h>
void plat::ReLaunch(int argc, char** argv) {
std::string Arg;
for (int c = 2; c <= argc; c++) {
Arg += " ";
Arg += argv[c - 1];
}
system("cls");
ShellExecute(nullptr, "runas", argv[0], Arg.c_str(), nullptr, SW_SHOWNORMAL);
ShowWindow(GetConsoleWindow(), 0);
std::this_thread::sleep_for(std::chrono::seconds(1));
exit(1);
}
void plat::URelaunch(int argc, char** argv) {
std::string Arg;
for (int c = 2; c <= argc; c++) {
Arg += " ";
Arg += argv[c - 1];
}
ShellExecute(nullptr, "open", argv[0], Arg.c_str(), nullptr, SW_SHOWNORMAL);
ShowWindow(GetConsoleWindow(), 0);
std::this_thread::sleep_for(std::chrono::seconds(1));
exit(1);
}
void plat::set_console_title(const std::string& title) {
SetConsoleTitleA(title);
}
void plat::clear_screen() {
system("cls");
}
LONG OpenKey(HKEY root,const char* path,PHKEY hKey){
return RegOpenKeyEx(root, reinterpret_cast<LPCSTR>(path), 0, KEY_READ, hKey);
}
#define MAX_KEY_LENGTH 255
#define MAX_VALUE_NAME 16383
std::string QueryKey(HKEY hKey,int ID){
TCHAR achKey[MAX_KEY_LENGTH]; // buffer for subkey name
DWORD cbName; // size of name string
TCHAR achClass[MAX_PATH] = TEXT(""); // buffer for class name
DWORD cchClassName = MAX_PATH; // size of class string
DWORD cSubKeys=0; // number of subkeys
DWORD cbMaxSubKey; // longest subkey size
DWORD cchMaxClass; // longest class string
DWORD cValues; // number of values for key
DWORD cchMaxValue; // longest value name
DWORD cbMaxValueData; // longest value data
DWORD cbSecurityDescriptor; // size of security descriptor
FILETIME ftLastWriteTime; // last write time
DWORD i, retCode;
TCHAR achValue[MAX_VALUE_NAME];
DWORD cchValue = MAX_VALUE_NAME;
retCode = RegQueryInfoKey(
hKey, // key handle
achClass, // buffer for class name
&cchClassName, // size of class string
nullptr, // reserved
&cSubKeys, // number of subkeys
&cbMaxSubKey, // longest subkey size
&cchMaxClass, // longest class string
&cValues, // number of values for this key
&cchMaxValue, // longest value name
&cbMaxValueData, // longest value data
&cbSecurityDescriptor, // security descriptor
&ftLastWriteTime); // last write time
BYTE* buffer = new BYTE[cbMaxValueData];
ZeroMemory(buffer, cbMaxValueData);
if (cSubKeys){
for (i=0; i<cSubKeys; i++){
cbName = MAX_KEY_LENGTH;
retCode = RegEnumKeyEx(hKey, i,achKey,&cbName,nullptr,nullptr,nullptr,&ftLastWriteTime);
if (retCode == ERROR_SUCCESS){
if(strcmp(achKey,"Steam App 284160") == 0){
return achKey;
}
}
}
}
if (cValues){
for (i=0, retCode = ERROR_SUCCESS; i<cValues; i++){
cchValue = MAX_VALUE_NAME;
achValue[0] = '\0';
retCode = RegEnumValue(hKey, i,achValue,&cchValue,nullptr,nullptr,nullptr,nullptr);
if (retCode == ERROR_SUCCESS ){
DWORD lpData = cbMaxValueData;
buffer[0] = '\0';
LONG dwRes = RegQueryValueEx(hKey, achValue, nullptr, nullptr, buffer, &lpData);
std::string data = (char *)(buffer);
std::string key = achValue;
switch (ID){
case 1: if(key == "SteamExe"){
auto p = data.find_last_of("/\\");
if(p != std::string::npos){
return data.substr(0,p);
}
}
break;
case 2: if(key == "Name" && data == "BeamNG.drive")return data;break;
case 3: if(key == "rootpath")return data;break;
case 4: if(key == "userpath_override")return data;
case 5: if(key == "Local AppData")return data;
default: break;
}
}
}
}
delete [] buffer;
return "";
}
std::string plat::get_game_dir_magically() {
std::string Result;
std::string K3 = R"(Software\BeamNG\BeamNG.drive)";
HKEY hKey;
LONG dwRegOPenKey = OpenKey(HKEY_CURRENT_USER, K3.c_str(), &hKey);
if (dwRegOPenKey == ERROR_SUCCESS) {
Result = QueryKey(hKey, 3);
if (Result.empty()) {
spdlog::error("Couldn't query key from HKEY_CURRENT_USER\\Software\\BeamNG\\BeamNG.drive");
Result = "";
}
} else {
spdlog::error("Couldn't open HKEY_CURRENT_USER\\Software\\BeamNG\\BeamNG.drive");
}
RegCloseKey(hKey);
return Result;
}
static int CALLBACK BrowseCallbackProc(HWND hwnd, UINT uMsg, LPARAM lParam, LPARAM lpData) {
if (uMsg == BFFM_INITIALIZED) {
std::string tmp = (const char*)lpData;
std::cout << "path: " << tmp << std::endl;
SendMessage(hwnd, BFFM_SETSELECTION, TRUE, lpData);
}
return 0;
}
std::string plat::ask_for_folder() {
TCHAR path[MAX_PATH];
const char* path_param = saved_path.c_str();
BROWSEINFO bi = { 0 };
bi.lpszTitle = ("Browse for folder...");
bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE;
bi.lpfn = BrowseCallbackProc;
bi.lParam = (LPARAM)path_param;
LPITEMIDLIST pidl = SHBrowseForFolder(&bi);
if (pidl != 0) {
// get the name of the folder and put it in path
SHGetPathFromIDList(pidl, path);
// free memory used
IMalloc* imalloc = 0;
if (SUCCEEDED(SHGetMalloc(&imalloc))) {
imalloc->Free(pidl);
imalloc->Release();
}
return path;
}
return "";
}
#endif

161
src/ServerNetwork.cpp Normal file
View File

@ -0,0 +1,161 @@
#include "ServerNetwork.h"
#include "ClientInfo.h"
#include "ImplementationInfo.h"
#include "Launcher.h"
#include "ProtocolVersion.h"
#include "ServerInfo.h"
#include <spdlog/spdlog.h>
ServerNetwork::ServerNetwork(Launcher& launcher, const ip::tcp::endpoint& ep)
: m_launcher(launcher)
, m_tcp_ep(ep) {
spdlog::debug("Server network created");
}
ServerNetwork::~ServerNetwork() {
spdlog::debug("Server network destroyed");
}
void ServerNetwork::run() {
boost::system::error_code ec;
m_tcp_socket.connect(m_tcp_ep, ec);
if (ec) {
spdlog::error("Failed to connect to [{}]:{}: {}", m_tcp_ep.address().to_string(), m_tcp_ep.port(), ec.message());
throw std::runtime_error(ec.message());
}
// start the connection by going to the identification state and sending
// the first packet in the identification protocol (protocol version)
m_state = bmp::State::Identification;
bmp::Packet version_packet {
.purpose = bmp::Purpose::ProtocolVersion,
.raw_data = std::vector<uint8_t>(6),
};
struct bmp::ProtocolVersion version {
.version = {
.major = 1,
.minor = 0,
.patch = 0,
},
};
version.serialize_to(version_packet.raw_data);
tcp_write(version_packet);
// main tcp recv loop
while (true) {
auto packet = tcp_read();
handle_packet(packet);
}
}
void ServerNetwork::handle_packet(const bmp::Packet& packet) {
switch (m_state) {
case bmp::State::None:
m_state = bmp::State::Identification;
[[fallthrough]];
case bmp::State::Identification:
handle_identification(packet);
break;
case bmp::State::Authentication:
break;
case bmp::State::ModDownload:
break;
case bmp::State::SessionSetup:
break;
case bmp::State::Playing:
break;
case bmp::State::Leaving:
break;
}
}
void ServerNetwork::handle_identification(const bmp::Packet& packet) {
switch (packet.purpose) {
case bmp::Purpose::ProtocolVersionOk: {
spdlog::debug("Protocol version ok");
bmp::Packet ci_packet {
.purpose = bmp::Purpose::ClientInfo,
.raw_data = std::vector<uint8_t>(1024),
};
// TODO: Game and mod version
struct bmp::ClientInfo ci {
.program_version = { .major = PRJ_VERSION_MAJOR, .minor = PRJ_VERSION_MINOR, .patch = PRJ_VERSION_PATCH },
.game_version = { .major = 4, .minor = 5, .patch = 6 },
.mod_version = { .major = 1, .minor = 2, .patch = 3 },
.implementation = bmp::ImplementationInfo {
.value = "Official BeamMP Launcher",
},
};
auto sz = ci.serialize_to(ci_packet.raw_data);
ci_packet.raw_data.resize(sz);
tcp_write(ci_packet);
break;
}
case bmp::Purpose::ProtocolVersionBad:
spdlog::error("The server rejected our protocol version!");
throw std::runtime_error("Protocol version rejected");
break;
case bmp::Purpose::ServerInfo: {
struct bmp::ServerInfo si { };
si.deserialize_from(packet.get_readable_data());
spdlog::debug("Connected to server implementation '{}' v{}.{}.{}",
si.implementation.value,
si.program_version.major,
si.program_version.minor,
si.program_version.patch);
break;
}
case bmp::Purpose::StateChangeAuthentication: {
spdlog::debug("Starting authentication");
m_state = bmp::State::Authentication;
break;
}
default:
spdlog::error("Got 0x{:x} in state {}. This is not allowed. Disconnecting", uint16_t(packet.purpose), int(m_state));
// todo: disconnect gracefully
break;
}
}
bmp::Packet ServerNetwork::tcp_read() {
bmp::Packet packet {};
std::vector<uint8_t> header_buffer(bmp::Header::SERIALIZED_SIZE);
read(m_tcp_socket, buffer(header_buffer));
bmp::Header hdr {};
hdr.deserialize_from(header_buffer);
// vector eaten up by now, recv again
packet.raw_data.resize(hdr.size);
read(m_tcp_socket, buffer(packet.raw_data));
packet.purpose = hdr.purpose;
packet.flags = hdr.flags;
return packet;
}
void ServerNetwork::tcp_write(bmp::Packet& packet) {
// finalize the packet (compress etc) and produce header
auto header = packet.finalize();
// serialize header
std::vector<uint8_t> header_data(bmp::Header::SERIALIZED_SIZE);
header.serialize_to(header_data);
// write header and packet data
write(m_tcp_socket, buffer(header_data));
write(m_tcp_socket, buffer(packet.raw_data));
}
bmp::Packet ServerNetwork::udp_read(ip::udp::endpoint& out_ep) {
// maximum we can ever expect from udp
static thread_local std::vector<uint8_t> s_buffer(std::numeric_limits<uint16_t>::max());
m_udp_socket.receive_from(buffer(s_buffer), out_ep, {});
bmp::Packet packet;
bmp::Header header {};
auto offset = header.deserialize_from(s_buffer);
packet.raw_data.resize(header.size);
std::copy(s_buffer.begin() + offset, s_buffer.begin() + offset + header.size, packet.raw_data.begin());
return packet;
}
void ServerNetwork::udp_write(bmp::Packet& packet) {
auto header = packet.finalize();
std::vector<uint8_t> data(header.size + bmp::Header::SERIALIZED_SIZE);
auto offset = header.serialize_to(data);
std::copy(packet.raw_data.begin(), packet.raw_data.end(), data.begin() + static_cast<long>(offset));
m_udp_socket.send_to(buffer(data), m_udp_ep, {});
}

45
src/ServerNetwork.h Normal file
View File

@ -0,0 +1,45 @@
#pragma once
#include "Packet.h"
#include "State.h"
#include <boost/asio.hpp>
using namespace boost::asio;
class Launcher;
class ServerNetwork {
public:
ServerNetwork(Launcher& launcher, const ip::tcp::endpoint& ep);
~ServerNetwork();
/// Starts and runs the connection to the server.
/// Calls back to the Launcher.
/// Blocking!
void run();
private:
/// Reads a single packet from the TCP stream. Blocks all other reads (not writes).
bmp::Packet tcp_read();
/// Writes the packet to the TCP stream. Blocks all other writes.
void tcp_write(bmp::Packet& packet);
/// Reads a packet from the given UDP socket, returning the client's endpoint as an out-argument.
bmp::Packet udp_read(ip::udp::endpoint& out_ep);
/// Sends a packet to the specified UDP endpoint via the UDP socket.
void udp_write(bmp::Packet& packet);
void handle_packet(const bmp::Packet& packet);
void handle_identification(const bmp::Packet& packet);
io_context m_io {};
ip::tcp::socket m_tcp_socket { m_io };
ip::udp::socket m_udp_socket { m_io };
bmp::State m_state {};
Launcher& m_launcher;
ip::tcp::endpoint m_tcp_ep;
ip::udp::endpoint m_udp_ep;
};

11
src/Sync.h Normal file
View File

@ -0,0 +1,11 @@
#pragma once
#include <boost/thread/synchronized_value.hpp>
#include <mutex>
/// This header provides convenience aliases for synchronization primitives.
template<typename T>
using Sync = boost::synchronized_value<T, std::recursive_mutex>;

37
src/Version.cpp Normal file
View File

@ -0,0 +1,37 @@
#include "Version.h"
#include <charconv>
#include <fmt/format.h>
#include <sstream>
Version::Version(uint8_t major, uint8_t minor, uint8_t patch)
: major(major)
, minor(minor)
, patch(patch) { }
Version::Version(const std::array<uint8_t, 3>& v)
: Version(v[0], v[1], v[2]) {
}
std::string Version::to_string() {
return fmt::format("{:d}.{:d}.{:d}", major, minor, patch);
}
bool Version::is_outdated(const Version& new_version) {
if (new_version.major > major) {
return true;
} else if (new_version.major == major && new_version.minor > minor) {
return true;
} else if (new_version.major == major && new_version.minor == minor && new_version.patch > patch) {
return true;
} else {
return false;
}
}
Version::Version(const std::string& str) {
std::stringstream ss(str);
std::string Part;
std::getline(ss, Part, '.');
std::from_chars(&*Part.begin(), &*Part.begin() + Part.size(), major);
std::from_chars(&*Part.begin(), &*Part.begin() + Part.size(), minor);
std::from_chars(&*Part.begin(), &*Part.begin() + Part.size(), patch);
}

16
src/Version.h Normal file
View File

@ -0,0 +1,16 @@
#pragma once
#include <cstdint>
#include <array>
#include <string>
struct Version {
uint8_t major {};
uint8_t minor {};
uint8_t patch {};
Version(uint8_t major, uint8_t minor, uint8_t patch);
Version(const std::array<uint8_t, 3>& v);
explicit Version(const std::string& str);
std::string to_string();
bool is_outdated(const Version& new_version);
};

125
src/main.cpp Normal file
View File

@ -0,0 +1,125 @@
#include "Launcher.h"
#include "Platform.h"
#include <iostream>
#include <thread>
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/spdlog.h>
/// Sets up a file- and console logger and makes it the default spdlog logger.
static void setup_logger(bool debug = false);
static std::shared_ptr<spdlog::logger> default_logger {};
int main(int argc, char** argv) {
bool enable_debug = false;
bool enable_dev = false;
int custom_port = 0;
std::string_view invalid_arg;
for (int i = 1; i < argc; ++i) {
std::string_view arg(argv[i]);
std::string_view next(i + 1 < argc ? argv[i + 1] : "");
// --debug flag enables debug printing in console
if (arg == "--debug") {
enable_debug = true;
// --dev enables developer mode (game is not started)
} else if (arg == "--dev") {
enable_dev = true;
} else if (arg == "0" && next == "0") {
enable_dev = true;
++i;
// an argument that is all digits and not 0 is a custom port, backwards-compat
} else if (std::all_of(arg.begin(), arg.end(), [](char c) { return std::isdigit(c); })) {
custom_port = std::stoi(arg.data());
} else {
invalid_arg = arg;
}
}
setup_logger(enable_debug || enable_dev);
spdlog::debug("Debug enabled");
if (!invalid_arg.empty()) {
spdlog::warn("Invalid argument passed via commandline switches: '{}'. This argument was ignored.", invalid_arg);
}
plat::clear_screen();
plat::set_console_title(fmt::format("BeamMP Launcher v{}.{}.{}", PRJ_VERSION_MAJOR, PRJ_VERSION_MINOR, PRJ_VERSION_PATCH));
spdlog::info("BeamMP Launcher v{}.{}.{} is a PRE-RELEASE build. Please report any errors immediately at https://github.com/BeamMP/BeamMP-Launcher.",
PRJ_VERSION_MAJOR, PRJ_VERSION_MINOR, PRJ_VERSION_PATCH);
Launcher launcher {};
std::filesystem::path arg0(argv[0]);
launcher.set_exe_name(arg0.filename().generic_string());
launcher.set_exe_path(arg0.parent_path());
if (custom_port > 0) {
launcher.set_port(custom_port);
}
if (!enable_dev) {
launcher.check_for_updates(argc, argv);
} else {
spdlog::debug("Skipping update check due to dev mode");
}
launcher.find_game();
if (!enable_dev) {
launcher.pre_game();
launcher.start_game();
}
launcher.start_network();
spdlog::info("Shutting down.");
}
void setup_logger(bool debug) {
auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
console_sink->set_pattern("[%H:%M:%S] [%^%l%$] %v");
if (debug) {
console_sink->set_level(spdlog::level::debug);
} else {
console_sink->set_level(spdlog::level::info);
}
auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>("Launcher.log", true);
file_sink->set_level(spdlog::level::trace);
default_logger = std::make_shared<spdlog::logger>(spdlog::logger("default", { console_sink, file_sink }));
default_logger->set_level(spdlog::level::trace);
default_logger->flush_on(spdlog::level::info);
spdlog::set_default_logger(default_logger);
spdlog::debug("Logger initialized");
}
/*
int oldmain(int argc, char* argv[]) {
#ifdef DEBUG
std::thread th(flush);
th.detach();
#endif
GetEP(argv[0]);
InitLauncher(argc, argv);
try {
LegitimacyCheck();
} catch (std::exception& e) {
fatal("Main 1 : " + std::string(e.what()));
}
StartProxy();
PreGame(GetGameDir());
InitGame(GetGameDir());
CoreNetwork();
/// TODO: make sure to use argv[0] for everything that should be in the same dir (mod down ect...)
}
*/

3
tests/test_main.cpp Normal file
View File

@ -0,0 +1,3 @@
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include <doctest/doctest.h>

18
vcpkg.json Normal file
View File

@ -0,0 +1,18 @@
{
"name": "my-project",
"version-string": "0.1.0",
"dependencies": [
"fmt",
"doctest",
"spdlog",
"openssl",
"cpp-httplib",
"boost-system",
"boost-iostreams",
"boost-process",
"boost-thread",
"nlohmann-json",
"cryptopp",
"zstd"
]
}