generated from AfonsoCMSousa/CPP-Template
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
20f2c3db79 |
@@ -1,4 +1,3 @@
|
||||
|
||||
*.a
|
||||
*.log
|
||||
*.so
|
||||
@@ -9,6 +8,3 @@
|
||||
/.DS_store
|
||||
/.env
|
||||
/imgui.ini
|
||||
|
||||
PlayerTracker
|
||||
*.json
|
||||
|
||||
+25
-140
@@ -1,57 +1,29 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
project(CPP_TEMPLATE VERSION 0.1.0 LANGUAGES C CXX)
|
||||
|
||||
# Set C++ standard
|
||||
set(CMAKE_CXX_STANDARD 23)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
# Set C standard
|
||||
set(CMAKE_C_STANDARD 17)
|
||||
set(CMAKE_C_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_C_EXTENSIONS OFF)
|
||||
|
||||
# Export compile commands for IDE support (clangd, etc.)
|
||||
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||
|
||||
# Create symlink to compile_commands.json in project root for LSP
|
||||
if(CMAKE_EXPORT_COMPILE_COMMANDS)
|
||||
add_custom_target(symlink_compile_commands ALL
|
||||
COMMAND ${CMAKE_COMMAND} -E create_symlink
|
||||
${CMAKE_BINARY_DIR}/compile_commands.json
|
||||
${CMAKE_SOURCE_DIR}/compile_commands.json
|
||||
COMMENT "Creating symlink to compile_commands.json in project root"
|
||||
)
|
||||
endif()
|
||||
|
||||
# Set output directories
|
||||
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
||||
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||
|
||||
# Build type defaults
|
||||
if(NOT CMAKE_BUILD_TYPE)
|
||||
set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Build type" FORCE)
|
||||
endif()
|
||||
# Add include directories
|
||||
include_directories(${CMAKE_SOURCE_DIR}/include)
|
||||
include_directories(${CMAKE_SOURCE_DIR}/libraries)
|
||||
|
||||
# Options
|
||||
option(ENABLE_SANITIZERS "Enable address and undefined behavior sanitizers" ON)
|
||||
option(ENABLE_STATIC_ANALYSIS "Enable static analysis warnings" ON)
|
||||
set(OUTPUT_NAME "" CACHE STRING "Name of the output executable (defaults to project name)")
|
||||
|
||||
# Gather source files (avoid GLOB_RECURSE - explicitly list files is better practice)
|
||||
# But keeping it for template flexibility
|
||||
# Gather all source files (.cpp, .c)
|
||||
file(GLOB_RECURSE PROJECT_SOURCES
|
||||
${CMAKE_SOURCE_DIR}/include/*.cpp
|
||||
${CMAKE_SOURCE_DIR}/include/*.c
|
||||
${CMAKE_SOURCE_DIR}/libraries/*.cpp
|
||||
${CMAKE_SOURCE_DIR}/libraries/*.c
|
||||
${CMAKE_SOURCE_DIR}/source/*.cpp
|
||||
${CMAKE_SOURCE_DIR}/source/*.c
|
||||
)
|
||||
|
||||
file(GLOB_RECURSE LIBRARY_SOURCES
|
||||
${CMAKE_SOURCE_DIR}/libraries/*.cpp
|
||||
${CMAKE_SOURCE_DIR}/libraries/*.c
|
||||
)
|
||||
|
||||
# Don't glob headers from include/ as sources (they should only be included)
|
||||
# Gather all header files (.hpp, .h)
|
||||
file(GLOB_RECURSE PROJECT_HEADERS
|
||||
${CMAKE_SOURCE_DIR}/include/*.hpp
|
||||
${CMAKE_SOURCE_DIR}/include/*.h
|
||||
@@ -61,51 +33,25 @@ file(GLOB_RECURSE PROJECT_HEADERS
|
||||
${CMAKE_SOURCE_DIR}/source/*.h
|
||||
)
|
||||
|
||||
# Combine all sources
|
||||
set(ALL_SOURCES ${PROJECT_SOURCES} ${LIBRARY_SOURCES})
|
||||
|
||||
# Determine executable name
|
||||
if(OUTPUT_NAME)
|
||||
set(EXECUTABLE_NAME ${OUTPUT_NAME})
|
||||
else()
|
||||
# Allow user to set output program name
|
||||
option(OUTPUT_NAME "Name of the output executable" "")
|
||||
if(OUTPUT_NAME STREQUAL "")
|
||||
set(EXECUTABLE_NAME ${PROJECT_NAME})
|
||||
else()
|
||||
set(EXECUTABLE_NAME ${OUTPUT_NAME})
|
||||
endif()
|
||||
|
||||
# Create executable
|
||||
add_executable(${EXECUTABLE_NAME} ${ALL_SOURCES})
|
||||
|
||||
# Set target properties
|
||||
set_target_properties(${EXECUTABLE_NAME} PROPERTIES
|
||||
OUTPUT_NAME ${EXECUTABLE_NAME}
|
||||
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}
|
||||
# Add executable with all sources
|
||||
add_executable(${EXECUTABLE_NAME}
|
||||
${PROJECT_SOURCES}
|
||||
)
|
||||
|
||||
# Include directories - use target-specific commands
|
||||
target_include_directories(${EXECUTABLE_NAME} PRIVATE
|
||||
${CMAKE_SOURCE_DIR}/include
|
||||
${CMAKE_SOURCE_DIR}/libraries
|
||||
)
|
||||
set_target_properties(${EXECUTABLE_NAME} PROPERTIES OUTPUT_NAME ${EXECUTABLE_NAME})
|
||||
|
||||
# Compiler-specific flags
|
||||
if(MSVC)
|
||||
target_compile_options(${EXECUTABLE_NAME} PRIVATE
|
||||
/W4 # Warning level 4
|
||||
/permissive- # Standards conformance
|
||||
/Zc:__cplusplus # Correct __cplusplus macro
|
||||
/Zc:inline # Remove unreferenced COMDAT
|
||||
/WX- # Don't treat warnings as errors by default
|
||||
)
|
||||
|
||||
if(ENABLE_STATIC_ANALYSIS)
|
||||
target_compile_options(${EXECUTABLE_NAME} PRIVATE /analyze)
|
||||
endif()
|
||||
|
||||
# MSVC debug flags
|
||||
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
|
||||
target_compile_options(${EXECUTABLE_NAME} PRIVATE /Zi /Od)
|
||||
endif()
|
||||
|
||||
else() # GCC/Clang
|
||||
# Enable warnings and extra diagnostics
|
||||
if (MSVC)
|
||||
target_compile_options(${EXECUTABLE_NAME} PRIVATE /W4 /permissive- /analyze)
|
||||
else()
|
||||
target_compile_options(${EXECUTABLE_NAME} PRIVATE
|
||||
-Wall
|
||||
-Wextra
|
||||
@@ -116,73 +62,12 @@ else() # GCC/Clang
|
||||
-Wuninitialized
|
||||
-Wunused
|
||||
-Werror=return-type
|
||||
-Wcast-align
|
||||
-Wformat=2
|
||||
-Wnull-dereference
|
||||
-fsanitize=address,undefined
|
||||
-g
|
||||
)
|
||||
|
||||
# Additional warnings for static analysis
|
||||
if(ENABLE_STATIC_ANALYSIS)
|
||||
target_compile_options(${EXECUTABLE_NAME} PRIVATE
|
||||
-Wcast-qual
|
||||
-Wdouble-promotion
|
||||
-Wold-style-cast
|
||||
)
|
||||
endif()
|
||||
|
||||
# Sanitizers (Debug builds)
|
||||
if(ENABLE_SANITIZERS AND CMAKE_BUILD_TYPE STREQUAL "Debug")
|
||||
# Check if sanitizers are available
|
||||
include(CheckCXXCompilerFlag)
|
||||
check_cxx_compiler_flag("-fsanitize=address" HAS_ASAN)
|
||||
check_cxx_compiler_flag("-fsanitize=undefined" HAS_UBSAN)
|
||||
|
||||
if(HAS_ASAN AND HAS_UBSAN)
|
||||
target_compile_options(${EXECUTABLE_NAME} PRIVATE
|
||||
-fsanitize=address,undefined,leak
|
||||
-fno-omit-frame-pointer
|
||||
-g
|
||||
)
|
||||
target_link_options(${EXECUTABLE_NAME} PRIVATE
|
||||
-fsanitize=address,undefined,leak
|
||||
)
|
||||
message(STATUS "Sanitizers enabled: address, undefined, leak")
|
||||
else()
|
||||
message(WARNING "Sanitizers requested but not available - skipping")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# Optimization flags for Release
|
||||
if(CMAKE_BUILD_TYPE STREQUAL "Release")
|
||||
target_compile_options(${EXECUTABLE_NAME} PRIVATE
|
||||
-O3
|
||||
-march=native
|
||||
-DNDEBUG
|
||||
)
|
||||
endif()
|
||||
|
||||
# Debug flags
|
||||
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
|
||||
target_compile_options(${EXECUTABLE_NAME} PRIVATE
|
||||
-O0
|
||||
-g3
|
||||
-ggdb
|
||||
)
|
||||
endif()
|
||||
target_link_options(${EXECUTABLE_NAME} PRIVATE -fsanitize=address,undefined)
|
||||
endif()
|
||||
|
||||
# Print configuration summary
|
||||
message(STATUS "=== Configuration Summary ===")
|
||||
message(STATUS "Project: ${PROJECT_NAME} v${PROJECT_VERSION}")
|
||||
message(STATUS "Build Type: ${CMAKE_BUILD_TYPE}")
|
||||
message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}")
|
||||
message(STATUS "C Standard: ${CMAKE_C_STANDARD}")
|
||||
message(STATUS "Executable Name: ${EXECUTABLE_NAME}")
|
||||
message(STATUS "Sanitizers: ${ENABLE_SANITIZERS}")
|
||||
message(STATUS "Static Analysis: ${ENABLE_STATIC_ANALYSIS}")
|
||||
message(STATUS "Compiler: ${CMAKE_CXX_COMPILER_ID} ${CMAKE_CXX_COMPILER_VERSION}")
|
||||
message(STATUS "============================")
|
||||
|
||||
# Optionally, enable testing
|
||||
# enable_testing()
|
||||
# add_subdirectory(tests)
|
||||
|
||||
Executable
BIN
Binary file not shown.
Executable
BIN
Binary file not shown.
@@ -1,250 +1,23 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Colors
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
BLUE='\033[0;34m'
|
||||
CYAN='\033[0;36m'
|
||||
MAGENTA='\033[0;35m'
|
||||
NC='\033[0m' # No Color
|
||||
BOLD='\033[1m'
|
||||
|
||||
# Unicode symbols
|
||||
CHECK="✓"
|
||||
CROSS="✗"
|
||||
ARROW="➜"
|
||||
GEAR="⚙"
|
||||
HAMMER="🔨"
|
||||
ROCKET="🚀"
|
||||
|
||||
# Default values
|
||||
BUILD_TYPE="Debug"
|
||||
CLEAN_BUILD=false
|
||||
VERBOSE=false
|
||||
JOBS=$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 4)
|
||||
|
||||
# Print functions
|
||||
print_header() {
|
||||
echo -e "${BOLD}${BLUE}╔════════════════════════════════════════════════════════╗${NC}"
|
||||
echo -e "${BOLD}${BLUE}║${NC} ${HAMMER} ${BOLD}${CYAN} C/C++ Project Builder${NC} ${BOLD}${BLUE}║${NC}"
|
||||
echo -e "${BOLD}${BLUE}╚════════════════════════════════════════════════════════╝${NC}"
|
||||
echo ""
|
||||
}
|
||||
|
||||
print_separator() {
|
||||
echo -e "${BLUE}────────────────────────────────────────────────────────${NC}"
|
||||
}
|
||||
|
||||
print_success() {
|
||||
echo -e "${GREEN}${CHECK}${NC} $1"
|
||||
}
|
||||
|
||||
print_error() {
|
||||
echo -e "${RED}${CROSS}${NC} $1"
|
||||
}
|
||||
|
||||
print_info() {
|
||||
echo -e "${CYAN}${ARROW}${NC} $1"
|
||||
}
|
||||
|
||||
print_step() {
|
||||
echo -e "${YELLOW}${GEAR}${NC} ${BOLD}$1${NC}"
|
||||
}
|
||||
|
||||
show_progress() {
|
||||
local duration=$1
|
||||
local prefix=$2
|
||||
local size=40
|
||||
already_done() { for ((done=0; done<$elapsed; done++)); do printf "▓"; done }
|
||||
remaining() { for ((remain=$elapsed; remain<$size; remain++)); do printf " "; done }
|
||||
percentage() { printf "| %s%%" $(( (($elapsed)*100)/($size)*100/100 )); }
|
||||
|
||||
for (( elapsed=1; elapsed<=$size; elapsed++ )); do
|
||||
printf "\r${CYAN}${prefix}${NC} [$(already_done)$(remaining)] $(percentage)"
|
||||
sleep $(echo "scale=3; $duration/$size" | bc)
|
||||
done
|
||||
printf "\n"
|
||||
}
|
||||
|
||||
usage() {
|
||||
echo -e "${BOLD}Usage:${NC} $0 [OPTIONS] <executable_name>"
|
||||
echo ""
|
||||
echo -e "${BOLD}Options:${NC}"
|
||||
echo -e " -r, --release Build in Release mode (default: Debug)"
|
||||
echo -e " -c, --clean Clean build directory before building"
|
||||
echo -e " -v, --verbose Verbose make output"
|
||||
echo -e " -j, --jobs <N> Number of parallel jobs (default: $JOBS)"
|
||||
echo -e " -h, --help Show this help message"
|
||||
echo ""
|
||||
echo -e "${BOLD}Examples:${NC}"
|
||||
echo -e " $0 myprogram"
|
||||
echo -e " $0 -r -j8 myprogram"
|
||||
echo -e " $0 --clean --release myprogram"
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Parse arguments
|
||||
POSITIONAL_ARGS=()
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case $1 in
|
||||
-r|--release)
|
||||
BUILD_TYPE="Release"
|
||||
shift
|
||||
;;
|
||||
-c|--clean)
|
||||
CLEAN_BUILD=true
|
||||
shift
|
||||
;;
|
||||
-v|--verbose)
|
||||
VERBOSE=true
|
||||
shift
|
||||
;;
|
||||
-j|--jobs)
|
||||
JOBS="$2"
|
||||
shift 2
|
||||
;;
|
||||
-h|--help)
|
||||
usage
|
||||
;;
|
||||
*)
|
||||
POSITIONAL_ARGS+=("$1")
|
||||
shift
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
set -- "${POSITIONAL_ARGS[@]}"
|
||||
|
||||
# Check if executable name is provided
|
||||
if [ -z "$1" ]; then
|
||||
print_header
|
||||
print_error "No executable name provided"
|
||||
echo ""
|
||||
usage
|
||||
echo "Error: Invalid Argument"
|
||||
echo "Usage: $0 <executable_name>"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
EXECUTABLE_NAME=$1
|
||||
|
||||
# Start build process
|
||||
print_header
|
||||
|
||||
# Build configuration info
|
||||
print_info "Build Configuration:"
|
||||
echo -e " ${BOLD}Executable:${NC} $EXECUTABLE_NAME"
|
||||
echo -e " ${BOLD}Build Type:${NC} $BUILD_TYPE"
|
||||
echo -e " ${BOLD}Jobs:${NC} $JOBS"
|
||||
echo -e " ${BOLD}Clean Build:${NC} $CLEAN_BUILD"
|
||||
echo ""
|
||||
print_separator
|
||||
echo ""
|
||||
|
||||
# Clean build directory if requested
|
||||
if [ "$CLEAN_BUILD" = true ] && [ -d "./build" ]; then
|
||||
print_step "Cleaning build directory..."
|
||||
rm -rf ./build
|
||||
print_success "Build directory cleaned"
|
||||
echo ""
|
||||
fi
|
||||
|
||||
# Create build directory
|
||||
if [ ! -d "./build" ]; then
|
||||
print_step "Creating build directory..."
|
||||
mkdir -p build
|
||||
print_success "Build directory created"
|
||||
else
|
||||
print_info "Using existing build directory"
|
||||
echo "Creating build directory..."
|
||||
mkdir build
|
||||
fi
|
||||
echo ""
|
||||
|
||||
# CMake configuration
|
||||
print_step "Configuring CMake..."
|
||||
print_separator
|
||||
echo ""
|
||||
|
||||
echo ">>> Building C++ Project <<<"
|
||||
cd ./build
|
||||
|
||||
CMAKE_CMD="cmake -DOUTPUT_NAME=$EXECUTABLE_NAME -DCMAKE_BUILD_TYPE=$BUILD_TYPE .."
|
||||
|
||||
if [ "$VERBOSE" = true ]; then
|
||||
eval $CMAKE_CMD
|
||||
else
|
||||
eval $CMAKE_CMD > /dev/null 2>&1
|
||||
fi
|
||||
|
||||
cmake -DOUTPUT_NAME=$1 ..
|
||||
echo ">>> Compiling... <<<"
|
||||
make
|
||||
if [ $? -ne 0 ]; then
|
||||
print_error "CMake configuration failed"
|
||||
echo "Error: Build failed"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
print_success "CMake configuration complete"
|
||||
echo ""
|
||||
|
||||
# Compilation
|
||||
print_step "Compiling project..."
|
||||
print_separator
|
||||
echo ""
|
||||
|
||||
MAKE_CMD="make -j$JOBS"
|
||||
if [ "$VERBOSE" = true ]; then
|
||||
MAKE_CMD="$MAKE_CMD VERBOSE=1"
|
||||
fi
|
||||
|
||||
START_TIME=$(date +%s)
|
||||
|
||||
if [ "$VERBOSE" = true ]; then
|
||||
eval $MAKE_CMD
|
||||
BUILD_RESULT=$?
|
||||
else
|
||||
eval $MAKE_CMD 2>&1 | tee build.log | while IFS= read -r line; do
|
||||
if echo "$line" | grep -q "\[.*%\]"; then
|
||||
printf "\r${CYAN}${ARROW}${NC} Compiling: %s" "$line"
|
||||
elif echo "$line" | grep -qE "error:|Error|ERROR"; then
|
||||
echo ""
|
||||
print_error "$line"
|
||||
fi
|
||||
done
|
||||
BUILD_RESULT=${PIPESTATUS[0]}
|
||||
fi
|
||||
|
||||
END_TIME=$(date +%s)
|
||||
BUILD_TIME=$((END_TIME - START_TIME))
|
||||
|
||||
echo ""
|
||||
|
||||
if [ $BUILD_RESULT -ne 0 ]; then
|
||||
print_error "Build failed!"
|
||||
echo ""
|
||||
print_info "Check build/build.log for details"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
print_success "Compilation complete (${BUILD_TIME}s)"
|
||||
echo ""
|
||||
|
||||
# Copy executable
|
||||
print_step "Copying executable to project root..."
|
||||
|
||||
if [ ! -f "./bin/$EXECUTABLE_NAME" ]; then
|
||||
print_error "Executable not found: ./bin/$EXECUTABLE_NAME"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cp ./bin/$EXECUTABLE_NAME ../
|
||||
print_success "Executable copied"
|
||||
echo ""
|
||||
|
||||
# Build summary
|
||||
print_separator
|
||||
echo -e "${BOLD}${GREEN}${ROCKET} Build Complete!${NC}"
|
||||
print_separator
|
||||
echo ""
|
||||
echo -e "${BOLD}Summary:${NC}"
|
||||
echo -e " ${BOLD}Executable:${NC} ./$EXECUTABLE_NAME"
|
||||
echo -e " ${BOLD}Build Type:${NC} $BUILD_TYPE"
|
||||
echo -e " ${BOLD}Build Time:${NC} ${BUILD_TIME}s"
|
||||
echo -e " ${BOLD}Binary Location:${NC} ./build/bin/$EXECUTABLE_NAME"
|
||||
|
||||
echo ""
|
||||
print_info "Run with: ${BOLD}./$EXECUTABLE_NAME${NC}"
|
||||
echo ""
|
||||
cp ./bin/$1 ../
|
||||
echo ">>> Build Complete <<<"
|
||||
echo ">>> Executable: $1 <<<"
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
build/compile_commands.json
|
||||
@@ -1,19 +0,0 @@
|
||||
#ifndef APP_CONFIG_HPP
|
||||
#define APP_CONFIG_HPP
|
||||
|
||||
#include <string>
|
||||
#include <cstdint>
|
||||
|
||||
struct app_info {
|
||||
// From args
|
||||
uint16_t app_id;
|
||||
uint16_t app_port_in;
|
||||
uint16_t app_port_out;
|
||||
|
||||
// From .env
|
||||
std::string app_api_socket_path;
|
||||
uint16_t max_players;
|
||||
std::string app_server_out_ip;
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -1,19 +0,0 @@
|
||||
#ifndef FILE_H
|
||||
#define FILE_H
|
||||
|
||||
#include <stdio.h>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <fstream>
|
||||
#include <stdexcept>
|
||||
#include <map>
|
||||
|
||||
#include "app.hpp"
|
||||
#include "server_structs.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
vector<string> read_file(const char *filePath);
|
||||
app_info parce_args(int argc, char *argv[]);
|
||||
|
||||
#endif
|
||||
@@ -1,193 +0,0 @@
|
||||
#ifndef HANDLE_HPP
|
||||
#define HANDLE_HPP
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include "file.hpp" // for parce_args
|
||||
#include "net.hpp" // for socket operations
|
||||
#include "server_structs.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
class PacketReader {
|
||||
private:
|
||||
const u_char *buffer_;
|
||||
size_t buffer_size_;
|
||||
size_t offset_ = 0;
|
||||
bool error_ = false;
|
||||
|
||||
public:
|
||||
PacketReader(); // TODO:
|
||||
~PacketReader(); // TODO:
|
||||
|
||||
bool read_uint8(uint8_t &value) {
|
||||
size_t __bytes = sizeof(value);
|
||||
|
||||
if (offset_ + __bytes > buffer_size_) {
|
||||
error_ = true;
|
||||
return false;
|
||||
}
|
||||
|
||||
memcpy(&value, buffer_ + offset_, sizeof(value));
|
||||
|
||||
offset_++;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool read_uint16(uint16_t &value) {
|
||||
size_t __bytes = sizeof(value);
|
||||
|
||||
if (offset_ + __bytes > buffer_size_) {
|
||||
error_ = true;
|
||||
return false;
|
||||
}
|
||||
|
||||
memcpy(&value, buffer_ + offset_, sizeof(value));
|
||||
value = ntohs(value);
|
||||
|
||||
offset_ += 2;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool read_uint32(uint32_t &value) {
|
||||
size_t __bytes = sizeof(value);
|
||||
|
||||
if (offset_ + __bytes > buffer_size_) {
|
||||
error_ = true;
|
||||
return false;
|
||||
}
|
||||
|
||||
memcpy(&value, buffer_ + offset_, sizeof(value));
|
||||
value = ntohl(value);
|
||||
|
||||
offset_ += 4;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool read_float(float &value) {
|
||||
size_t __bytes = sizeof(value);
|
||||
|
||||
if (offset_ + __bytes > buffer_size_) {
|
||||
error_ = true;
|
||||
return false;
|
||||
}
|
||||
|
||||
uint32_t v_int;
|
||||
memcpy(&v_int, buffer_ + offset_, sizeof(v_int));
|
||||
v_int = ntohl(v_int);
|
||||
|
||||
memcpy(&value, &v_int, sizeof(value));
|
||||
|
||||
offset_ += 4;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool read_string_utf32l(string &value) {
|
||||
uint8_t __length;
|
||||
if (!read_uint8(__length))
|
||||
return false;
|
||||
|
||||
if (offset_ + (__length * sizeof(uint32_t)) > buffer_size_) {
|
||||
error_ = true;
|
||||
return false;
|
||||
}
|
||||
|
||||
value.clear();
|
||||
for (size_t i = 0; i < __length; i++) {
|
||||
uint32_t codeunit;
|
||||
if (!read_uint32(codeunit))
|
||||
return false;
|
||||
|
||||
if (codeunit == 0) {
|
||||
break; // null terminator
|
||||
}
|
||||
|
||||
value.push_back(static_cast<char>(codeunit));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool has_error() const {
|
||||
return error_;
|
||||
}
|
||||
};
|
||||
|
||||
class ProtocolHandler {
|
||||
private:
|
||||
trackAtributes track_info_;
|
||||
carAtributes player_info_[64];
|
||||
|
||||
public:
|
||||
ProtocolHandler();
|
||||
~ProtocolHandler();
|
||||
|
||||
bool handle_new_session(PacketReader &reader) {
|
||||
|
||||
if (!reader.read_uint8(track_info_.protocol_version))
|
||||
return false;
|
||||
if (!reader.read_uint8(track_info_.session_index))
|
||||
return false;
|
||||
if (!reader.read_uint8(track_info_.current_session_index))
|
||||
return false;
|
||||
if (!reader.read_uint8(track_info_.session_count))
|
||||
return false;
|
||||
|
||||
/*
|
||||
* str_len_8 = read_uint8((const u_int8_t *)buffer, recv_bytes, &offset, &ok);
|
||||
read_utf32le_string((const u_int8_t *)buffer, recv_bytes, &offset, trackInfo.server_name, str_len_8, &ok);
|
||||
|
||||
str_len_8 = read_uint8((const u_int8_t *)buffer, recv_bytes, &offset, &ok);
|
||||
read_string((const u_int8_t *)buffer, recv_bytes, &offset, trackInfo.track, str_len_8, &ok);
|
||||
|
||||
str_len_8 = read_uint8((const u_int8_t *)buffer, recv_bytes, &offset, &ok);
|
||||
read_string((const u_int8_t *)buffer, recv_bytes, &offset, trackInfo.track_config, str_len_8, &ok);
|
||||
|
||||
str_len_8 = read_uint8((const u_int8_t *)buffer, recv_bytes, &offset, &ok);
|
||||
read_string((const u_int8_t *)buffer, recv_bytes, &offset, trackInfo.session_name, str_len_8, &ok);
|
||||
|
||||
trackInfo.typ = read_uint8((const u_int8_t *)buffer, recv_bytes, &offset, &ok);
|
||||
trackInfo.time = read_uint16((const u_int8_t *)buffer, recv_bytes, &offset, &ok);
|
||||
trackInfo.laps = read_uint16((const u_int8_t *)buffer, recv_bytes, &offset, &ok);
|
||||
trackInfo.wait_time = read_uint16((const u_int8_t *)buffer, recv_bytes, &offset, &ok);
|
||||
trackInfo.ambient_temp = read_uint8((const u_int8_t *)buffer, recv_bytes, &offset, &ok);
|
||||
trackInfo.road_temp = read_uint8((const u_int8_t *)buffer, recv_bytes, &offset, &ok);
|
||||
|
||||
str_len_8 = read_uint8((const u_int8_t *)buffer, recv_bytes, &offset, &ok);
|
||||
read_string((const u_int8_t *)buffer, recv_bytes, &offset, trackInfo.weather_graphics, str_len_8, &ok);
|
||||
*/
|
||||
|
||||
if (!reader.read_string_utf32l(track_info_.server_name))
|
||||
return false;
|
||||
if (!reader.read_string_utf32l(track_info_.track))
|
||||
return false;
|
||||
if (!reader.read_string_utf32l(track_info_.track_config))
|
||||
return false;
|
||||
if (!reader.read_string_utf32l(track_info_.session_name))
|
||||
return false;
|
||||
if (!reader.read_uint8(track_info_.typ))
|
||||
return false;
|
||||
if (!reader.read_uint16(track_info_.time))
|
||||
return false;
|
||||
if (!reader.read_uint16(track_info_.laps))
|
||||
return false;
|
||||
if (!reader.read_uint16(track_info_.wait_time))
|
||||
return false;
|
||||
if (!reader.read_uint8(track_info_.ambient_temp))
|
||||
return false;
|
||||
if (!reader.read_uint8(track_info_.road_temp))
|
||||
return false;
|
||||
if (!reader.read_string_utf32l(track_info_.weather_graphics))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
};
|
||||
#endif // HANDLE_HPP
|
||||
@@ -1,23 +0,0 @@
|
||||
#ifndef LOG_H
|
||||
#define LOG_H
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdarg.h>
|
||||
#include <time.h>
|
||||
|
||||
typedef enum {
|
||||
LOG_INFO,
|
||||
LOG_DEBUG,
|
||||
LOG_WARN,
|
||||
LOG_ERROR
|
||||
} LogLevel;
|
||||
|
||||
void log_print(LogLevel level, const char* format, ...);
|
||||
|
||||
#define log_info(...) log_print(LOG_INFO, __VA_ARGS__)
|
||||
#define log_debug(...) log_print(LOG_DEBUG, __VA_ARGS__)
|
||||
#define log_warn(...) log_print(LOG_WARN, __VA_ARGS__)
|
||||
#define log_error(...) log_print(LOG_ERROR, __VA_ARGS__)
|
||||
|
||||
#endif // LOG_H
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
#ifndef MAPPER_HPP
|
||||
#define MAPPER_HPP
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstddef>
|
||||
|
||||
#include "parcer.h"
|
||||
#include "server_structs.h"
|
||||
|
||||
// INFO: This is basically a identity mapper between raw byte buffer and structs defined in server_structs.h
|
||||
class Mapper {
|
||||
private:
|
||||
const uint_least8_t *buffer;
|
||||
size_t buffer_size;
|
||||
size_t offset;
|
||||
bool ok;
|
||||
|
||||
public:
|
||||
Mapper(const uint_least8_t *buf, size_t buf_size);
|
||||
|
||||
uint8_t get_message_type();
|
||||
bool is_ok() const { return ok; }
|
||||
|
||||
void parse_new_session(trackAtributes &track);
|
||||
void parse_new_connection(carAtributes &car);
|
||||
void parse_connection_closed(carAtributes &car);
|
||||
void parse_car_update(carAtributes &car);
|
||||
void parse_car_info(carAtributes &car);
|
||||
void parse_lap_completed(uint8_t &car_id, uint32_t &lap_time, uint32_t &cuts);
|
||||
void parse_collision_event(uint8_t &car1, uint8_t &car2, uint8_t &event_type);
|
||||
void parse_chat(uint8_t &car_id, char *message, size_t max_len);
|
||||
void parse_client_loaded(uint8_t &car_id);
|
||||
|
||||
void set_size(size_t size) { this->buffer_size = size; }
|
||||
void update_buffer(const uint8_t *buf, size_t size) {
|
||||
this->buffer = buf;
|
||||
this->buffer_size = size;
|
||||
reset();
|
||||
}
|
||||
private:
|
||||
// INFO: Reset the offset to 1 because the first byte is message type
|
||||
void reset() { offset = 1; ok = true; }
|
||||
};
|
||||
|
||||
#endif // MAPPER_HPP
|
||||
@@ -1,52 +0,0 @@
|
||||
#ifndef NET_HPP
|
||||
#define NET_HPP
|
||||
|
||||
#include <arpa/inet.h>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/un.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "log.h"
|
||||
#include "server_structs.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
class Socket {
|
||||
private:
|
||||
// Socket file descriptor
|
||||
int sock_server;
|
||||
int sock_unix;
|
||||
struct sockaddr_in server_addr;
|
||||
struct sockaddr_un server_addr_unix;
|
||||
|
||||
// Server port for input (listening)
|
||||
int server_port_input;
|
||||
char buffer[1024];
|
||||
|
||||
// Socket Data
|
||||
api_packet packet_data;
|
||||
|
||||
public:
|
||||
Socket();
|
||||
~Socket();
|
||||
|
||||
void connect_server(const char *ip, uint16_t port);
|
||||
void bind_server(const char *ip, uint16_t port);
|
||||
void send_server();
|
||||
void send_server(const api_packet &data);
|
||||
void send_server(const void *data, size_t len);
|
||||
ssize_t receive_server(void *buffer, size_t len);
|
||||
|
||||
void connect_unix(const char *ip, uint16_t port);
|
||||
void send_unix();
|
||||
void send_unix(const api_packet &data);
|
||||
void set_packet(const api_packet &data);
|
||||
|
||||
api_packet create_packet(uint8_t tracker_id);
|
||||
api_packet get_packet();
|
||||
};
|
||||
|
||||
#endif // NET_HPP
|
||||
@@ -1,141 +0,0 @@
|
||||
#include "parcer.h"
|
||||
#include "server_structs.h"
|
||||
#include <sys/types.h>
|
||||
|
||||
int ensure(size_t recv_len, size_t offset, size_t need) {
|
||||
return (offset + need <= recv_len);
|
||||
}
|
||||
|
||||
u_int8_t read_uint8(const u_int8_t *buf, size_t recv_len, size_t *offset, int *ok) {
|
||||
if (!ensure(recv_len, *offset, sizeof(uint8_t))) {
|
||||
*ok = 0;
|
||||
return 0;
|
||||
}
|
||||
u_int8_t v;
|
||||
memcpy(&v, buf + *offset, sizeof(v));
|
||||
*offset += sizeof(v);
|
||||
return v;
|
||||
}
|
||||
|
||||
u_int16_t read_uint16(const u_int8_t *buf, size_t recv_len, size_t *offset, int *ok) {
|
||||
if (!ensure(recv_len, *offset, sizeof(uint16_t))) {
|
||||
*ok = 0;
|
||||
return 0;
|
||||
}
|
||||
u_int16_t v;
|
||||
memcpy(&v, buf + *offset, sizeof(v));
|
||||
*offset += sizeof(v);
|
||||
return (u_int16_t)ntohs(v);
|
||||
}
|
||||
|
||||
u_int32_t read_uint32(const u_int8_t *buf, size_t recv_len, size_t *offset, int *ok) {
|
||||
if (!ensure(recv_len, *offset, sizeof(uint32_t))) {
|
||||
*ok = 0;
|
||||
return 0;
|
||||
}
|
||||
u_int32_t v;
|
||||
memcpy(&v, buf + *offset, sizeof(v));
|
||||
*offset += sizeof(v);
|
||||
return (u_int32_t)ntohl(v);
|
||||
}
|
||||
|
||||
int32_t read_int32(const u_int8_t *buf, size_t recv_len, size_t *offset, int *ok) {
|
||||
if (!ensure(recv_len, *offset, sizeof(int32_t))) {
|
||||
*ok = 0;
|
||||
return 0;
|
||||
}
|
||||
int32_t v;
|
||||
memcpy(&v, buf + *offset, sizeof(v));
|
||||
*offset += sizeof(v);
|
||||
return (int32_t)ntohl(v);
|
||||
}
|
||||
|
||||
float read_float(const u_int8_t *buf, size_t recv_len, size_t *offset, int *ok) {
|
||||
if (!ensure(recv_len, *offset, sizeof(float))) {
|
||||
*ok = 0;
|
||||
return 0.0f;
|
||||
}
|
||||
u_int32_t v_int;
|
||||
memcpy(&v_int, buf + *offset, sizeof(v_int));
|
||||
*offset += sizeof(v_int);
|
||||
v_int = ntohl(v_int);
|
||||
float v_float;
|
||||
memcpy(&v_float, &v_int, sizeof(v_float));
|
||||
return v_float;
|
||||
}
|
||||
|
||||
void read_bytes(const u_int8_t *buf, size_t recv_len, size_t *offset, u_int8_t *out, size_t len, int *ok) {
|
||||
if (!ensure(recv_len, *offset, len)) {
|
||||
*ok = 0;
|
||||
return;
|
||||
}
|
||||
memcpy(out, buf + *offset, len);
|
||||
*offset += len;
|
||||
}
|
||||
|
||||
void read_utf32le_string(const uint8_t *buffer, size_t buf_size, size_t *offset, char *dest, size_t max_len, int *ok) {
|
||||
size_t i = *offset;
|
||||
size_t j = 0;
|
||||
|
||||
while (i + 3 < buf_size && j < max_len) {
|
||||
uint32_t codeunit = buffer[i] | (buffer[i + 1] << 8) | (buffer[i + 2] << 16) | (buffer[i + 3] << 24);
|
||||
|
||||
if (codeunit == 0) {
|
||||
i += 4; // termina a string
|
||||
break;
|
||||
}
|
||||
|
||||
if (codeunit < 0x80) {
|
||||
dest[j++] = (char)codeunit;
|
||||
} else {
|
||||
dest[j++] = '?'; // substitui caracteres fora de ASCII
|
||||
}
|
||||
|
||||
i += 4;
|
||||
}
|
||||
|
||||
dest[j] = '\0';
|
||||
*offset = i;
|
||||
*ok = 1;
|
||||
}
|
||||
|
||||
void read_utf16le_string(const uint8_t *buffer, size_t buf_size, size_t *offset, char *dest, size_t max_len, int *ok) {
|
||||
size_t i = *offset;
|
||||
size_t j = 0;
|
||||
|
||||
while (i + 1 < buf_size && j < max_len - 1) {
|
||||
uint16_t codeunit = buffer[i] | (buffer[i + 1] << 8);
|
||||
|
||||
if (codeunit == 0) {
|
||||
i += 2; // termina a string
|
||||
break;
|
||||
}
|
||||
|
||||
if (codeunit < 0x80) {
|
||||
dest[j++] = (char)codeunit;
|
||||
} else {
|
||||
dest[j++] = '?'; // substitui caracteres fora de ASCII
|
||||
}
|
||||
|
||||
i += 2;
|
||||
}
|
||||
|
||||
dest[j] = '\0';
|
||||
*offset = i;
|
||||
*ok = 1;
|
||||
}
|
||||
|
||||
void read_string(const u_int8_t *buf, size_t recv_len, size_t *offset, char *out, size_t len, int *ok) {
|
||||
if (!ensure(recv_len, *offset, len)) {
|
||||
*ok = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
for (size_t i = 0; i <= len; i++) {
|
||||
out[i] = (char)buf[*offset + i];
|
||||
}
|
||||
out[len] = '\0'; // Ensure null termination
|
||||
*offset += len;
|
||||
*ok = 1;
|
||||
}
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
#ifndef PARCER_H
|
||||
#define PARCER_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "server_structs.h"
|
||||
|
||||
// Ensures that there are at least 'need' bytes available in the buffer
|
||||
// starting from 'offset'. Returns 1 if enough bytes are available, 0 otherwise.
|
||||
int ensure(size_t recv_len, size_t offset, size_t need);
|
||||
|
||||
// Reads an 8-bit unsigned integer from the buffer.
|
||||
// Advances the offset by 1 byte.
|
||||
u_int8_t read_uint8(const u_int8_t *buf, size_t recv_len, size_t *offset, int *ok);
|
||||
|
||||
// Reads a 16-bit unsigned integer from the buffer in network byte order.
|
||||
// Advances the offset by 2 bytes.
|
||||
u_int16_t read_uint16(const u_int8_t *buf, size_t recv_len, size_t *offset, int *ok);
|
||||
|
||||
// Reads a 16-bit unsigned integer from the buffer in little-endian byte order.
|
||||
// Advances the offset by 2 bytes.
|
||||
u_int16_t read_uint16_le(const u_int8_t *buf, size_t recv_len, size_t *offset, int *ok);
|
||||
|
||||
// Reads a 32-bit unsigned integer from the buffer in network byte order.
|
||||
// Advances the offset by 4 bytes.
|
||||
u_int32_t read_uint32(const u_int8_t *buf, size_t recv_len, size_t *offset, int *ok);
|
||||
|
||||
// Reads a 32-bit signed integer from the buffer in network byte order.
|
||||
// Advances the offset by 4 bytes.
|
||||
int32_t read_int32(const u_int8_t *buf, size_t recv_len, size_t *offset, int *ok);
|
||||
|
||||
// Reads a 32-bit float from the buffer in network byte order.
|
||||
// Advances the offset by 4 bytes.
|
||||
float read_float(const u_int8_t *buf, size_t recv_len, size_t *offset, int *ok);
|
||||
|
||||
// Reads a fixed number of bytes into the output buffer.
|
||||
// The output buffer must be at least 'len' bytes long.
|
||||
void read_bytes(const u_int8_t *buf, size_t recv_len, size_t *offset, u_int8_t *out, size_t len, int *ok);
|
||||
|
||||
// Reads a length-prefixed string. The length is a single byte.
|
||||
// The string is not null-terminated in the buffer, but the function
|
||||
void read_utf32le_string(const uint8_t *buffer, size_t buf_size, size_t *offset, char *dest, size_t max_len, int *ok);
|
||||
|
||||
// reads up to max_len - 1 characters and null-terminates the destination buffer.
|
||||
// The string is encoded in UTF-32LE.
|
||||
void read_utf16le_string(const uint8_t *buffer, size_t buf_size, size_t *offset, char *dest, size_t max_len, int *ok);
|
||||
|
||||
// Reads a null-terminated string from the buffer.
|
||||
// The string is read into the output buffer, which must be at least max_len bytes long
|
||||
void read_string(const u_int8_t *buf, size_t recv_len, size_t *offset, char *out, size_t max_len, int *ok);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // PARCER_H
|
||||
@@ -1,62 +0,0 @@
|
||||
#ifndef PARCER_H
|
||||
#define PARCER_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "server_structs.hpp"
|
||||
|
||||
// Ensures that there are at least 'need' bytes available in the buffer
|
||||
// starting from 'offset'. Returns 1 if enough bytes are available, 0 otherwise.
|
||||
int ensure(size_t recv_len, size_t offset, size_t need);
|
||||
|
||||
// Reads an 8-bit unsigned integer from the buffer.
|
||||
// Advances the offset by 1 byte.
|
||||
u_int8_t read_uint8(const u_int8_t *buf, size_t recv_len, size_t *offset, int *ok);
|
||||
|
||||
// Reads a 16-bit unsigned integer from the buffer in network byte order.
|
||||
// Advances the offset by 2 bytes.
|
||||
u_int16_t read_uint16(const u_int8_t *buf, size_t recv_len, size_t *offset, int *ok);
|
||||
|
||||
// Reads a 32-bit unsigned integer from the buffer in network byte order.
|
||||
// Advances the offset by 4 bytes.
|
||||
u_int32_t read_uint32(const u_int8_t *buf, size_t recv_len, size_t *offset, int *ok);
|
||||
|
||||
// Reads a 32-bit signed integer from the buffer in network byte order.
|
||||
// Advances the offset by 4 bytes.
|
||||
int32_t read_int32(const u_int8_t *buf, size_t recv_len, size_t *offset, int *ok);
|
||||
|
||||
// Reads a 32-bit float from the buffer in network byte order.
|
||||
// Advances the offset by 4 bytes.
|
||||
float read_float(const u_int8_t *buf, size_t recv_len, size_t *offset, int *ok);
|
||||
|
||||
// Reads a fixed number of bytes into the output buffer.
|
||||
// The output buffer must be at least 'len' bytes long.
|
||||
void read_bytes(const u_int8_t *buf, size_t recv_len, size_t *offset, u_int8_t *out, size_t len, int *ok);
|
||||
|
||||
// Reads a length-prefixed string. The length is a single byte.
|
||||
// The string is not null-terminated in the buffer, but the function
|
||||
void read_utf32le_string(const uint8_t *buffer, size_t buf_size, size_t *offset, char *dest, size_t max_len, int *ok);
|
||||
|
||||
// reads up to max_len - 1 characters and null-terminates the destination buffer.
|
||||
// The string is encoded in UTF-32LE.
|
||||
void read_utf16le_string(const uint8_t *buffer, size_t buf_size, size_t *offset, char *dest, size_t max_len, int *ok);
|
||||
|
||||
// Reads a null-terminated string from the buffer.
|
||||
// The string is read into the output buffer, which must be at least max_len bytes long
|
||||
void read_string(const u_int8_t *buf, size_t recv_len, size_t *offset, char *out, size_t max_len, int *ok);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // PARCER_H
|
||||
+40
-234
@@ -1,247 +1,53 @@
|
||||
#ifndef SERVER_STRUCTS_H
|
||||
#define SERVER_STRUCTS_H
|
||||
|
||||
#include <sys/cdefs.h>
|
||||
#include <sys/types.h>
|
||||
#include <cstdint>
|
||||
struct handshake {
|
||||
// [not used in the current Remote Telemtry version by AC]
|
||||
// In future versions it will identify the platform type of the client.
|
||||
// This will be used to adjust a specific behaviour for each platform. (eIPadDevice for now (1))
|
||||
int32_t identifier;
|
||||
|
||||
#define MAX_PLAYERS 64
|
||||
// [not used in the current Remote Telemtry version by AC]
|
||||
// In future version this field will identify the AC Remote Telemetry version that the device expects to speak with.
|
||||
int32_t version;
|
||||
|
||||
typedef struct handshake {
|
||||
// [not used in the current Remote Telemtry version by AC]
|
||||
// In future versions it will identify the platform type of the client.
|
||||
// This will be used to adjust a specific behaviour for each platform. (eIPadDevice for now (1))
|
||||
int32_t identifier;
|
||||
// This is the type of operation required by the client.
|
||||
// The following operations are now available:
|
||||
// ----------------------------------------------------------------
|
||||
// HANDSHAKE = 0 :
|
||||
// This operation identifier must be set when the client wants to start the comunication.
|
||||
//
|
||||
// SUBSCRIBE_UPDATE = 1 :
|
||||
// This operation identifier must be set when the client wants to be updated from the specific ACServer.
|
||||
//
|
||||
// SUBSCRIBE_SPOT = 2 :
|
||||
// This operation identifier must be set when the client wants to be updated from the specific ACServer just for SPOT Events (e.g.: the end of a lap).
|
||||
//
|
||||
// DISMISS = 3 :
|
||||
// This operation identifier must be set when the client wants to leave the comunication with ACServer.
|
||||
int32_t operationId;
|
||||
} __attribute__((packed));
|
||||
|
||||
// [not used in the current Remote Telemtry version by AC]
|
||||
// In future version this field will identify the AC Remote Telemetry version that the device expects to speak with.
|
||||
int32_t version;
|
||||
struct handshackerResponse{
|
||||
// is the name of the car that the player is driving on the AC Server
|
||||
char carName[50];
|
||||
|
||||
// This is the type of operation required by the client.
|
||||
// The following operations are now available:
|
||||
// ----------------------------------------------------------------
|
||||
// HANDSHAKE = 0 :
|
||||
// This operation identifier must be set when the client wants to start the comunication.
|
||||
//
|
||||
// SUBSCRIBE_UPDATE = 1 :
|
||||
// This operation identifier must be set when the client wants to be updated from the specific ACServer.
|
||||
//
|
||||
// SUBSCRIBE_SPOT = 2 :
|
||||
// This operation identifier must be set when the client wants to be updated from the specific ACServer just for SPOT Events (e.g.: the end of a lap).
|
||||
//
|
||||
// DISMISS = 3 :
|
||||
// This operation identifier must be set when the client wants to leave the comunication with ACServer.
|
||||
int32_t operationId;
|
||||
} __attribute__((packed)) handshake;
|
||||
// is the name of the driver running on the AC Server
|
||||
char driverName[50];
|
||||
|
||||
typedef struct handshackerResponse {
|
||||
// is the name of the car that the player is driving on the AC Server
|
||||
char carName[50];
|
||||
// for now is just 4242, this code will identify different status,
|
||||
// as “NOT AVAILABLE” for connection
|
||||
int32_t identifier;
|
||||
|
||||
// is the name of the driver running on the AC Server
|
||||
char driverName[50];
|
||||
// for now is set to 1, this will identify the version running on the AC Server
|
||||
int32_t version;
|
||||
|
||||
// for now is just 4242, this code will identify different status,
|
||||
// as “NOT AVAILABLE” for connection
|
||||
int32_t identifier;
|
||||
// is the name of the track on the AC Server
|
||||
char trackName[50];
|
||||
|
||||
// for now is set to 1, this will identify the version running on the AC Server
|
||||
int32_t version;
|
||||
|
||||
// is the name of the track on the AC Server
|
||||
char trackName[50];
|
||||
|
||||
// is the track configuration on the AC Server
|
||||
char trackConfig[50];
|
||||
} __attribute__((packed)) handshackerResponse;
|
||||
|
||||
typedef struct postion {
|
||||
float x;
|
||||
float y;
|
||||
float z;
|
||||
} __attribute__((packed)) postion;
|
||||
|
||||
typedef enum flag {
|
||||
NO_FLAG = 0,
|
||||
YELLOW_FLAG = 1,
|
||||
BLUE_FLAG = 2,
|
||||
BLACK_FLAG = 3,
|
||||
CHECKERED_FLAG = 4,
|
||||
} __attribute__((packed)) flag;
|
||||
|
||||
typedef struct carAtributes {
|
||||
// Related to ACSP_CAR_INFO
|
||||
char isConnected; // 1 = connected, 0 = disconnected
|
||||
char isLoading; // 1 = loading, 0 = not isLoading
|
||||
|
||||
char *car_model;
|
||||
char *car_skin;
|
||||
char *driver_name;
|
||||
char *driver_team;
|
||||
char *driver_GUID;
|
||||
|
||||
// Related to ACSP_CAR_UPDATE
|
||||
u_int8_t carID;
|
||||
postion position;
|
||||
postion velocity;
|
||||
u_int8_t carGear;
|
||||
u_int16_t carRPM;
|
||||
u_int32_t lap_time;
|
||||
u_int32_t cuts;
|
||||
u_int32_t total_cuts;
|
||||
u_int32_t total_cuts_alltime;
|
||||
u_int16_t total_laps_completed;
|
||||
u_int16_t contacts;
|
||||
u_int16_t total_contacts;
|
||||
|
||||
flag current_flag; // TODO: implement flag status updates
|
||||
// TAG:3
|
||||
|
||||
float normalizedSplinePos;
|
||||
} __attribute__((packed)) carAtributes;
|
||||
|
||||
typedef struct carAtributesAPI {
|
||||
// Related to ACSP_CAR_INFO
|
||||
char isConnected; // 1 = connected, 0 = disconnected
|
||||
char isLoading; // 1 = loading, 0 = not isLoading
|
||||
|
||||
char car_model[64];
|
||||
char car_skin[64];
|
||||
char driver_name[64];
|
||||
char driver_team[64];
|
||||
char driver_GUID[64];
|
||||
|
||||
// Related to ACSP_CAR_UPDATE
|
||||
u_int8_t carID;
|
||||
postion position;
|
||||
postion velocity;
|
||||
u_int8_t carGear;
|
||||
u_int16_t carRPM;
|
||||
u_int32_t lap_time;
|
||||
u_int32_t cuts;
|
||||
u_int32_t total_cuts;
|
||||
u_int32_t total_cuts_alltime;
|
||||
u_int16_t total_laps_completed;
|
||||
u_int16_t contacts;
|
||||
u_int16_t total_contacts;
|
||||
|
||||
flag current_flag; // TODO: implement flag status updates
|
||||
// TAG:3
|
||||
|
||||
float normalizedSplinePos;
|
||||
} __attribute__((packed)) carAtributesAPI;
|
||||
|
||||
|
||||
typedef enum SessionType {
|
||||
PRACTICE = 0,
|
||||
RACE = 1,
|
||||
QUALIFYING = 2,
|
||||
} __attribute__((packed)) SessionType;
|
||||
|
||||
typedef struct trackAtributes {
|
||||
u_int8_t protocol_version;
|
||||
|
||||
u_int8_t session_index;
|
||||
u_int8_t current_session_index;
|
||||
u_int8_t session_count;
|
||||
SessionType session_type;
|
||||
|
||||
char *server_name;
|
||||
char *track;
|
||||
char *track_config;
|
||||
char *session_name;
|
||||
|
||||
u_int8_t typ;
|
||||
u_int16_t time;
|
||||
u_int16_t laps;
|
||||
u_int16_t wait_time;
|
||||
u_int8_t ambient_temp;
|
||||
u_int8_t road_temp;
|
||||
|
||||
char *weather_graphics;
|
||||
u_int32_t elapsed_ms;
|
||||
} __attribute__((packed)) trackAtributes;
|
||||
|
||||
typedef struct trackAtributesAPI {
|
||||
u_int8_t protocol_version;
|
||||
|
||||
u_int8_t session_index;
|
||||
u_int8_t current_session_index;
|
||||
u_int8_t session_count;
|
||||
SessionType session_type;
|
||||
|
||||
char server_name[128];
|
||||
char track[64];
|
||||
char track_config[64];
|
||||
char session_name[64];
|
||||
|
||||
u_int8_t typ;
|
||||
u_int16_t time;
|
||||
u_int16_t laps;
|
||||
u_int16_t wait_time;
|
||||
u_int8_t ambient_temp;
|
||||
u_int8_t road_temp;
|
||||
|
||||
char weather_graphics[64];
|
||||
u_int32_t elapsed_ms;
|
||||
} __attribute__((packed)) trackAtributesAPI;
|
||||
|
||||
typedef struct api_packet {
|
||||
char message_type; // ACSP_MessageType
|
||||
u_int8_t tracker_id;
|
||||
u_int8_t connected_players;
|
||||
|
||||
carAtributesAPI cars[64];
|
||||
trackAtributesAPI track_info;
|
||||
|
||||
} __attribute__((packed)) api_packet;
|
||||
|
||||
enum ACSP_MessageType {
|
||||
// ============================
|
||||
// PROTOCOL VERSION
|
||||
// ============================
|
||||
// DONE: Update this when protocol changes
|
||||
PROTOCOL_VERSION = 4,
|
||||
|
||||
// ============================
|
||||
// SERVER → CLIENT MESSAGES
|
||||
// ============================
|
||||
ACSP_NEW_SESSION = 50,
|
||||
ACSP_NEW_CONNECTION = 51,
|
||||
ACSP_CONNECTION_CLOSED = 52,
|
||||
ACSP_CAR_UPDATE = 53,
|
||||
ACSP_CAR_INFO = 54, // Response to ACSP_GET_CAR_INFO
|
||||
ACSP_END_SESSION = 55,
|
||||
ACSP_VERSION = 56,
|
||||
ACSP_CHAT = 57,
|
||||
ACSP_CLIENT_LOADED = 58,
|
||||
ACSP_SESSION_INFO = 59,
|
||||
ACSP_ERROR = 60,
|
||||
ACSP_LAP_COMPLETED = 73,
|
||||
|
||||
// ============================
|
||||
// EVENTS
|
||||
// ============================
|
||||
ACSP_CLIENT_EVENT = 130,
|
||||
|
||||
// ============================
|
||||
// EVENT TYPES
|
||||
// ============================
|
||||
ACSP_CE_COLLISION_WITH_CAR = 10,
|
||||
ACSP_CE_COLLISION_WITH_ENV = 11,
|
||||
|
||||
// ============================
|
||||
// CLIENT → SERVER COMMANDS
|
||||
// ============================
|
||||
ACSP_REALTIMEPOS_INTERVAL = 200,
|
||||
ACSP_GET_CAR_INFO = 201,
|
||||
ACSP_SEND_CHAT = 202, // Sends chat to one car
|
||||
ACSP_BROADCAST_CHAT = 203, // Sends chat to everybody
|
||||
ACSP_GET_SESSION_INFO = 204,
|
||||
ACSP_SET_SESSION_INFO = 205,
|
||||
ACSP_KICK_USER = 206,
|
||||
ACSP_NEXT_SESSION = 207,
|
||||
ACSP_RESTART_SESSION = 208,
|
||||
ACSP_ADMIN_COMMAND = 209 // Send message plus a string
|
||||
};
|
||||
// is the track configuration on the AC Server
|
||||
char trackConfig[50];
|
||||
} __attribute__((packed));
|
||||
|
||||
#endif // SERVER_STRUCTS_H
|
||||
|
||||
@@ -1,158 +0,0 @@
|
||||
#ifndef SERVER_STRUCTS_H
|
||||
#define SERVER_STRUCTS_H
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <string>
|
||||
#include <sys/cdefs.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
typedef struct app_info {
|
||||
// From args
|
||||
u_int16_t app_id;
|
||||
u_int16_t app_port_in;
|
||||
u_int16_t app_port_out;
|
||||
|
||||
// From .env
|
||||
const char *app_api_socket_path;
|
||||
u_int16_t max_players;
|
||||
const char *app_server_out_ip;
|
||||
} __attribute__((packed)) app_info;
|
||||
|
||||
typedef struct postion {
|
||||
float x;
|
||||
float y;
|
||||
float z;
|
||||
} __attribute__((packed)) postion;
|
||||
|
||||
typedef enum flag {
|
||||
NO_FLAG = 0,
|
||||
YELLOW_FLAG = 1,
|
||||
BLUE_FLAG = 2,
|
||||
BLACK_FLAG = 3,
|
||||
CHECKERED_FLAG = 4,
|
||||
} __attribute__((packed)) flag;
|
||||
|
||||
typedef struct carAtributes {
|
||||
// Related to ACSP_CAR_INFO
|
||||
u_char isConnected; // 1 = connected, 0 = disconnected
|
||||
u_char isLoading; // 1 = loading, 0 = not isLoading
|
||||
|
||||
string car_model[64];
|
||||
string car_skin[64];
|
||||
string driver_name[64];
|
||||
string driver_team[64];
|
||||
string driver_GUID[64];
|
||||
|
||||
// Related to ACSP_CAR_UPDATE
|
||||
u_int8_t carID;
|
||||
postion position;
|
||||
postion velocity;
|
||||
u_int8_t carGear;
|
||||
u_int16_t carRPM;
|
||||
u_int32_t lap_time;
|
||||
u_int32_t cuts;
|
||||
u_int32_t total_cuts;
|
||||
u_int32_t total_cuts_alltime;
|
||||
u_int16_t total_laps_completed;
|
||||
u_int16_t contacts;
|
||||
u_int16_t total_contacts;
|
||||
|
||||
flag current_flag; // TODO: implement flag status updates
|
||||
// TAG:3
|
||||
|
||||
float normalizedSplinePos;
|
||||
} __attribute__((packed)) carAtributes;
|
||||
|
||||
|
||||
typedef enum SessionType {
|
||||
PRACTICE = 0,
|
||||
RACE = 1,
|
||||
QUALIFYING = 2,
|
||||
} __attribute__((packed)) SessionType;
|
||||
|
||||
typedef struct trackAtributes{
|
||||
u_int8_t protocol_version;
|
||||
|
||||
u_int8_t session_index;
|
||||
u_int8_t current_session_index;
|
||||
u_int8_t session_count;
|
||||
SessionType session_type;
|
||||
|
||||
string server_name;
|
||||
string track[64];
|
||||
string track_config[64];
|
||||
string session_name[64];
|
||||
|
||||
u_int8_t typ;
|
||||
u_int16_t time;
|
||||
u_int16_t laps;
|
||||
u_int16_t wait_time;
|
||||
u_int8_t ambient_temp;
|
||||
u_int8_t road_temp;
|
||||
|
||||
string weather_graphics[64];
|
||||
u_int32_t elapsed_ms;
|
||||
} __attribute__((packed)) trackAtributes;
|
||||
|
||||
typedef struct api_packet {
|
||||
u_char message_type; // ACSP_MessageType
|
||||
u_int8_t tracker_id;
|
||||
u_int8_t connected_players;
|
||||
|
||||
carAtributes cars[64];
|
||||
trackAtributes track_info;
|
||||
} __attribute__((packed)) api_packet;
|
||||
|
||||
enum ACSP_MessageType {
|
||||
// ============================
|
||||
// PROTOCOL VERSION
|
||||
// ============================
|
||||
PROTOCOL_VERSION = 4,
|
||||
|
||||
// ============================
|
||||
// SERVER → CLIENT MESSAGES
|
||||
// ============================
|
||||
ACSP_NEW_SESSION = 50,
|
||||
ACSP_NEW_CONNECTION = 51,
|
||||
ACSP_CONNECTION_CLOSED = 52,
|
||||
ACSP_CAR_UPDATE = 53,
|
||||
ACSP_CAR_INFO = 54, // Response to ACSP_GET_CAR_INFO
|
||||
ACSP_END_SESSION = 55,
|
||||
ACSP_VERSION = 56,
|
||||
ACSP_CHAT = 57,
|
||||
ACSP_CLIENT_LOADED = 58,
|
||||
ACSP_SESSION_INFO = 59,
|
||||
ACSP_ERROR = 60,
|
||||
ACSP_LAP_COMPLETED = 73,
|
||||
|
||||
// ============================
|
||||
// EVENTS
|
||||
// ============================
|
||||
ACSP_CLIENT_EVENT = 130,
|
||||
|
||||
// ============================
|
||||
// EVENT TYPES
|
||||
// ============================
|
||||
ACSP_CE_COLLISION_WITH_CAR = 10,
|
||||
ACSP_CE_COLLISION_WITH_ENV = 11,
|
||||
|
||||
// ============================
|
||||
// CLIENT → SERVER COMMANDS
|
||||
// ============================
|
||||
ACSP_REALTIMEPOS_INTERVAL = 200,
|
||||
ACSP_GET_CAR_INFO = 201,
|
||||
ACSP_SEND_CHAT = 202, // Sends chat to one car
|
||||
ACSP_BROADCAST_CHAT = 203, // Sends chat to everybody
|
||||
ACSP_GET_SESSION_INFO = 204,
|
||||
ACSP_SET_SESSION_INFO = 205,
|
||||
ACSP_KICK_USER = 206,
|
||||
ACSP_NEXT_SESSION = 207,
|
||||
ACSP_RESTART_SESSION = 208,
|
||||
ACSP_ADMIN_COMMAND = 209 // Send message plus a string
|
||||
};
|
||||
|
||||
#endif // SERVER_STRUCTS_H
|
||||
@@ -1,33 +0,0 @@
|
||||
#ifndef SESSION_MANAGER_HPP
|
||||
#define SESSION_MANAGER_HPP
|
||||
|
||||
#include "server_structs.h"
|
||||
#include <string.h>
|
||||
#include <cstring>
|
||||
|
||||
class SessionManager {
|
||||
private:
|
||||
trackAtributes track_info;
|
||||
carAtributes players[MAX_PLAYERS];
|
||||
u_int8_t connected_players;
|
||||
u_int8_t server_id;
|
||||
|
||||
public:
|
||||
SessionManager(u_int8_t sid);
|
||||
|
||||
void on_new_session(const trackAtributes &track);
|
||||
void on_player_connected(const carAtributes &car);
|
||||
void on_player_finished_loading(u_int8_t car_id);
|
||||
void on_player_disconnected(u_int8_t car_id);
|
||||
void on_car_update(const carAtributes &car);
|
||||
void on_lap_completed(u_int8_t car_id, u_int32_t lap_time, u_int32_t cuts);
|
||||
void on_collision(u_int8_t car1, u_int8_t car2);
|
||||
|
||||
api_packet build_packet(u_int8_t message_type);
|
||||
|
||||
const trackAtributes& get_track_info() const { return track_info; }
|
||||
const carAtributes* get_players() const { return players; }
|
||||
u_int8_t get_connected_players() const { return connected_players; }
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,84 @@
|
||||
#include "socket.h"
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
|
||||
int connect_udp_socket(const char* ip, uint16_t port) {
|
||||
#ifdef _WIN32
|
||||
static int wsa_initialized = 0;
|
||||
if (!wsa_initialized) {
|
||||
WSADATA wsaData;
|
||||
if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
|
||||
fprintf(stderr, "WSAStartup failed\n");
|
||||
return -1;
|
||||
}
|
||||
wsa_initialized = 1;
|
||||
}
|
||||
#endif
|
||||
|
||||
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
|
||||
if (sockfd < 0) {
|
||||
perror("socket creation failed");
|
||||
return -1;
|
||||
}
|
||||
|
||||
struct sockaddr_in servaddr;
|
||||
memset(&servaddr, 0, sizeof(servaddr));
|
||||
|
||||
servaddr.sin_family = AF_INET;
|
||||
servaddr.sin_port = htons(port);
|
||||
servaddr.sin_addr.s_addr = inet_addr(ip);
|
||||
|
||||
if (connect(sockfd, (const struct sockaddr*)&servaddr, sizeof(servaddr)) < 0) {
|
||||
perror("connection to the server failed");
|
||||
CLOSESOCKET(sockfd);
|
||||
return -1;
|
||||
}
|
||||
|
||||
return sockfd;
|
||||
}
|
||||
|
||||
int bind_udp_socket(int sockfd, const char* ip, uint16_t port) {
|
||||
struct sockaddr_in servaddr;
|
||||
memset(&servaddr, 0, sizeof(servaddr));
|
||||
|
||||
servaddr.sin_family = AF_INET;
|
||||
servaddr.sin_addr.s_addr = inet_addr(ip);
|
||||
servaddr.sin_port = htons(port);
|
||||
|
||||
if (bind(sockfd, (const struct sockaddr*)&servaddr, sizeof(servaddr)) < 0) {
|
||||
perror("bind failed");
|
||||
CLOSESOCKET(sockfd);
|
||||
return -1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
ssize_t send_udp_message(int sockfd, const char *message, const char *dest_ip, uint16_t dest_port) {
|
||||
struct sockaddr_in destaddr;
|
||||
memset(&destaddr, 0, sizeof(destaddr));
|
||||
|
||||
destaddr.sin_family = AF_INET;
|
||||
destaddr.sin_port = htons(dest_port);
|
||||
destaddr.sin_addr.s_addr = inet_addr(dest_ip);
|
||||
|
||||
#ifdef _WIN32
|
||||
int n = sendto(sockfd, message, (int)strlen(message), 0, (const struct sockaddr*)&destaddr, sizeof(destaddr));
|
||||
#else
|
||||
ssize_t n = sendto(sockfd, message, strlen(message), 0, (const struct sockaddr*)&destaddr, sizeof(destaddr));
|
||||
#endif
|
||||
|
||||
if (n < 0) {
|
||||
perror("sendto failed");
|
||||
return -1;
|
||||
}
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
void cleanup_sockets() {
|
||||
WSACleanup();
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
#include "socket.h"
|
||||
|
||||
// =========================
|
||||
// UDP SOCKET FUCNTIONS
|
||||
// =========================
|
||||
|
||||
// Create a UDP socket
|
||||
// @return: Socket file descriptor, or -1 on error
|
||||
int create_udp_socket(void) {
|
||||
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
|
||||
if (sockfd < 0) {
|
||||
perror("[!] socket() failed");
|
||||
return -1;
|
||||
}
|
||||
return sockfd;
|
||||
}
|
||||
|
||||
// Create a UDP socket and connect it to a specific IP and port
|
||||
// Used for sending data (no bind needed)
|
||||
// @param ip: Destination IP address as a string
|
||||
// @return: Socket file descriptor, or -1 on error
|
||||
int connect_udp_socket(const char *ip, uint16_t port) {
|
||||
int sockfd = create_udp_socket();
|
||||
if (sockfd < 0)
|
||||
return -1;
|
||||
|
||||
struct sockaddr_in servaddr;
|
||||
memset(&servaddr, 0, sizeof(servaddr));
|
||||
servaddr.sin_family = AF_INET;
|
||||
servaddr.sin_port = htons(port);
|
||||
servaddr.sin_addr.s_addr = inet_addr(ip);
|
||||
|
||||
if (connect(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
|
||||
perror("[!] connect() failed");
|
||||
close(sockfd);
|
||||
return -1;
|
||||
}
|
||||
|
||||
printf("[+] Connected UDP socket to %s:%d\n", ip, port);
|
||||
return sockfd;
|
||||
}
|
||||
|
||||
// Create and bind a UDP socket to a local IP and port
|
||||
// Used for listening for incoming data
|
||||
// @param ip: Local IP address to bind to
|
||||
// @param port: Local port to bind to
|
||||
// @return: Socket file descriptor, or -1 on error
|
||||
int create_bound_udp_socket(const char *ip, uint16_t port) {
|
||||
int sockfd = create_udp_socket();
|
||||
if (sockfd < 0)
|
||||
return -1;
|
||||
|
||||
struct sockaddr_in addr;
|
||||
memset(&addr, 0, sizeof(addr));
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_port = htons(port);
|
||||
addr.sin_addr.s_addr = inet_addr(ip);
|
||||
|
||||
if (bind(sockfd, (const struct sockaddr *)&addr, sizeof(addr)) < 0) {
|
||||
perror("[!] bind() failed");
|
||||
close(sockfd);
|
||||
return -1;
|
||||
}
|
||||
|
||||
printf("[+] Bound UDP socket on %s:%d\n", ip, port);
|
||||
return sockfd;
|
||||
}
|
||||
|
||||
// Send a UDP message to the specified IP and port
|
||||
// @param sockfd: Socket file descriptor
|
||||
// @param message: Message to send
|
||||
// @param dest_ip: Destination IP address as a string
|
||||
// @param dest_port: Destination port
|
||||
// @return: Number of bytes sent, or -1 on error
|
||||
ssize_t send_udp_message(int sockfd, const char *message, const char *dest_ip, uint16_t dest_port) {
|
||||
struct sockaddr_in destaddr;
|
||||
memset(&destaddr, 0, sizeof(destaddr));
|
||||
destaddr.sin_family = AF_INET;
|
||||
destaddr.sin_port = htons(dest_port);
|
||||
destaddr.sin_addr.s_addr = inet_addr(dest_ip);
|
||||
|
||||
ssize_t n = sendto(sockfd, message, strlen(message), 0, (const struct sockaddr *)&destaddr, sizeof(destaddr));
|
||||
if (n < 0) {
|
||||
perror("[!] sendto() failed");
|
||||
return -1;
|
||||
}
|
||||
|
||||
printf("[+] Sent %zd bytes to %s:%d\n", n, dest_ip, dest_port);
|
||||
return n;
|
||||
}
|
||||
+16
-13
@@ -5,20 +5,24 @@
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#include <ctype.h>
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#pragma comment(lib, "ws2_32.lib") // link Winsock
|
||||
#pragma comment(lib, "ws2_32.lib")
|
||||
#define CLOSESOCKET closesocket
|
||||
#else
|
||||
#include <arpa/inet.h>
|
||||
#include <netinet/in.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <unistd.h>
|
||||
#define CLOSESOCKET close
|
||||
#endif
|
||||
|
||||
// =========================
|
||||
@@ -27,13 +31,12 @@ extern "C" {
|
||||
// Server hosts a UDP socket at 127.0.0.1:12000
|
||||
// Client sends a message to the server at 11000
|
||||
|
||||
// UDP socket creation & management
|
||||
int create_udp_socket(void);
|
||||
int connect_udp_socket(const char *ip, uint16_t port);
|
||||
int create_bound_udp_socket(const char *ip, uint16_t port);
|
||||
|
||||
// UDP messaging
|
||||
ssize_t send_udp_message(int sockfd, const char *message, const char *dest_ip, uint16_t dest_port);
|
||||
int bind_udp_socket(int sockfd, const char *ip, uint16_t port);
|
||||
|
||||
ssize_t send_udp_message(int sockfd, const char *message, const char *dest_ip,
|
||||
uint16_t dest_port);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
#ifndef SOCKET_H
|
||||
#define SOCKET_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#pragma comment(lib, "ws2_32.lib") // link Winsock
|
||||
#else
|
||||
#include <arpa/inet.h>
|
||||
#include <netinet/in.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
// =========================
|
||||
// UDP SOCKET FUCNTIONS
|
||||
// =========================
|
||||
// Server hosts a UDP socket at 127.0.0.1:12000
|
||||
// Client sends a message to the server at 11000
|
||||
|
||||
// UDP socket creation & management
|
||||
int create_udp_socket(void);
|
||||
int connect_udp_socket(const char *ip, uint16_t port);
|
||||
int create_bound_udp_socket(const char *ip, uint16_t port);
|
||||
|
||||
// UDP messaging
|
||||
ssize_t send_udp_message(int sockfd, const char *message, const char *dest_ip, uint16_t dest_port);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // SOCKET_H
|
||||
@@ -1,58 +0,0 @@
|
||||
#include "file.hpp"
|
||||
|
||||
vector<string> read_file(const char *filePath) {
|
||||
ifstream file(filePath);
|
||||
if (!file.is_open()) {
|
||||
return vector<string>();
|
||||
}
|
||||
|
||||
vector<string> lines;
|
||||
string line;
|
||||
|
||||
while (getline(file, line)) {
|
||||
lines.push_back(line);
|
||||
}
|
||||
|
||||
file.close();
|
||||
return lines;
|
||||
}
|
||||
|
||||
app_info parce_args(int argc, char *argv[]) {
|
||||
// example
|
||||
// ./player_tracker 130 12000 13000
|
||||
// -id -serverin -serverout
|
||||
app_info __processed_info;
|
||||
|
||||
if (argc <= 1) {
|
||||
throw invalid_argument("No argc provided");
|
||||
} else if (argc != 4) {
|
||||
throw invalid_argument("Invalid number of args provided");
|
||||
}
|
||||
|
||||
__processed_info.app_id = (u_int16_t)atoi(argv[1]);
|
||||
__processed_info.app_port_in = (u_int16_t)atoi(argv[2]);
|
||||
__processed_info.app_port_out = (u_int16_t)atoi(argv[3]);
|
||||
|
||||
// Parce .env
|
||||
vector<string> __read_lines = read_file("./.env");
|
||||
map<string, string> __env_args;
|
||||
|
||||
for (size_t i = 0; i < __read_lines.size() - 1; i++) {
|
||||
string token = __read_lines[i].substr(0, __read_lines[i].find(" = "));
|
||||
|
||||
__read_lines[i].erase(0, __read_lines[i].find(" = ") + 3);
|
||||
|
||||
__env_args[token] = __read_lines[i];
|
||||
}
|
||||
|
||||
// DEBUG
|
||||
// for (const auto& [key, value] : __env_args) {
|
||||
// std::cout << '[' << key << "] = " << value << "; ";
|
||||
// }
|
||||
|
||||
__processed_info.app_api_socket_path = __env_args["API_SOCKET_PATH"];
|
||||
__processed_info.max_players = (u_int16_t)atoi(__env_args["MAX_PLAYERS"].c_str());
|
||||
__processed_info.app_server_out_ip = __env_args["SERVER_OUT_IP"];
|
||||
|
||||
return __processed_info;
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
#include "log.h"
|
||||
|
||||
void log_print(LogLevel level, const char* format, ...) {
|
||||
time_t now = time(NULL);
|
||||
struct tm *t = localtime(&now);
|
||||
|
||||
const char* level_tag;
|
||||
switch(level) {
|
||||
case LOG_INFO: level_tag = "INF"; break;
|
||||
case LOG_DEBUG: level_tag = "DBG"; break;
|
||||
case LOG_ERROR: level_tag = "ERR"; break;
|
||||
case LOG_WARN: level_tag = "WRN"; break;
|
||||
default: level_tag = "UNK"; break;
|
||||
}
|
||||
|
||||
// %02d ensures it prints "05" instead of just "5"
|
||||
printf("[%02d:%02d:%02d %s] ",
|
||||
t->tm_hour, t->tm_min, t->tm_sec, level_tag);
|
||||
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
vprintf(format, args); // vprintf takes a va_list instead of ...
|
||||
va_end(args);
|
||||
}
|
||||
+97
-143
@@ -1,154 +1,108 @@
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <ctype.h>
|
||||
#include <iostream>
|
||||
#include <signal.h>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#pragma comment(lib, "ws2_32.lib") // only needed for MSVC
|
||||
#else
|
||||
#include <sys/socket.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
#include <vector>
|
||||
#endif
|
||||
|
||||
#include "app.hpp" // for app_info struct
|
||||
#include "file.hpp" // for parce_args
|
||||
#include "log.h" // for logging
|
||||
#include "net.hpp" // for socket operations
|
||||
#include "server_structs.h" // for api_packet and ACSP_MessageType
|
||||
#include "session.hpp" // for SessionManager
|
||||
#include "mapper.hpp" // for Mapper
|
||||
#include "server_structs.h"
|
||||
#include "socket.h"
|
||||
|
||||
const u_int8_t UPDATE_INTERVAL = 120; // in milliseconds
|
||||
// Cross-platform close macro
|
||||
#ifdef _WIN32
|
||||
#define CLOSESOCKET closesocket
|
||||
#else
|
||||
#define CLOSESOCKET close
|
||||
#endif
|
||||
|
||||
using namespace std;
|
||||
const int SERVER_OUT_PORT = 9996;
|
||||
const int SERVER_IN_PORT = 11000;
|
||||
const char* SERVER_OUT_IP = "127.0.0.1";
|
||||
|
||||
volatile bool STOP_PROGRAM = false;
|
||||
int main() {
|
||||
|
||||
void signal_handler(int signum) {
|
||||
if (signum == SIGINT || signum == SIGTERM) {
|
||||
STOP_PROGRAM = true;
|
||||
}
|
||||
#ifdef _WIN32
|
||||
WSADATA wsaData;
|
||||
if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
|
||||
fprintf(stderr, "[-] WSAStartup failed\n");
|
||||
return -1;
|
||||
}
|
||||
#endif
|
||||
|
||||
printf("[+] Starting server...\n");
|
||||
printf("[+] Server listening on port %d\n", SERVER_IN_PORT);
|
||||
printf("[+] Server sending to %s:%d\n", SERVER_OUT_IP, SERVER_OUT_PORT);
|
||||
|
||||
// Create UDP socket
|
||||
int sock_FD = connect_udp_socket(SERVER_OUT_IP, SERVER_OUT_PORT);
|
||||
if (sock_FD < 0) {
|
||||
fprintf(stderr, "[-] Failed to create UDP socket\n");
|
||||
#ifdef _WIN32
|
||||
WSACleanup();
|
||||
#endif
|
||||
return -1;
|
||||
}
|
||||
|
||||
handshake hs;
|
||||
hs.identifier = 1;
|
||||
hs.operationId = 1;
|
||||
hs.version = 0;
|
||||
|
||||
printf("[+] Sending handshake message...\t");
|
||||
ssize_t bytes_sent = send_udp_message((int)sock_FD, (const char*)&hs, SERVER_OUT_IP, uint16_t(SERVER_OUT_PORT));
|
||||
if (bytes_sent >= 0) {
|
||||
printf("OK (%zd bytes)\n", bytes_sent);
|
||||
} else {
|
||||
fprintf(stderr, "ERROR.\n");
|
||||
CLOSESOCKET(sock_FD);
|
||||
#ifdef _WIN32
|
||||
WSACleanup();
|
||||
#endif
|
||||
return -2;
|
||||
}
|
||||
|
||||
uint8_t buffer[512]; // bigger than struct
|
||||
ssize_t bytes_received = recv(sock_FD, (char*)buffer, sizeof(buffer), 0);
|
||||
|
||||
if (bytes_received >= sizeof(handshackerResponse)) {
|
||||
|
||||
// Convert strings from big endian to little endian if necessary
|
||||
|
||||
handshackerResponse resp;
|
||||
memcpy(&resp, buffer, sizeof(handshackerResponse));
|
||||
|
||||
printf("[+] Received handshake response:\n");
|
||||
printf(" Car: ");
|
||||
for (int i = 0; i < 50; i++) {
|
||||
printf("%c", isprint(resp.carName[i]) ? resp.carName[i] : '.');
|
||||
}
|
||||
printf("\n");
|
||||
|
||||
printf(" Driver: %s\n", resp.driverName);
|
||||
printf(" Identifier: %d\n", resp.identifier);
|
||||
printf(" Version: %d\n", resp.version);
|
||||
printf(" Track: %s\n", resp.trackName);
|
||||
printf(" Config: %s\n", resp.trackConfig);
|
||||
} else {
|
||||
printf("[!] Packet too short for handshake response (%zd bytes)\n", bytes_received);
|
||||
}
|
||||
|
||||
CLOSESOCKET(sock_FD);
|
||||
|
||||
#ifdef _WIN32
|
||||
WSACleanup();
|
||||
#endif
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
app_info app = parce_args(argc, argv);
|
||||
api_packet packet;
|
||||
|
||||
Socket sock;
|
||||
|
||||
SessionManager session_manager(app.app_id);
|
||||
|
||||
uint8_t buffer[1028];
|
||||
Mapper map(buffer, 1028);
|
||||
|
||||
trackAtributes track;
|
||||
|
||||
track.server_name = new char[256];
|
||||
track.track = new char[64];
|
||||
track.track_config = new char[64];
|
||||
track.session_name = new char[64];
|
||||
track.weather_graphics = new char[64];
|
||||
|
||||
try {
|
||||
// Connect socket to API
|
||||
// sock.connect_unix(app.app_api_socket_path.c_str(), app.app_port_out);
|
||||
// Connect socket to Server
|
||||
sock.connect_server(app.app_server_out_ip.c_str(), app.app_port_in);
|
||||
sock.bind_server("127.0.0.1", app.app_port_out);
|
||||
|
||||
// Await server for initial data
|
||||
sock.receive_server(buffer, sizeof(buffer));
|
||||
log_info("Connected to server, awaiting version confirmation...\n");
|
||||
|
||||
if (buffer[0] == ACSP_VERSION) {
|
||||
log_info("Server version confirmed. Sending update rate request @ %ums\n", UPDATE_INTERVAL);
|
||||
} else {
|
||||
throw runtime_error("Did not receive version confirmation from server.");
|
||||
}
|
||||
|
||||
char request[516] = {0};
|
||||
request[0] = ACSP_REALTIMEPOS_INTERVAL;
|
||||
request[1] = UPDATE_INTERVAL;
|
||||
|
||||
sock.send_server(request, sizeof(request));
|
||||
log_debug("Info:\n");
|
||||
log_debug("\t\tApp ID: %d\n", app.app_id);
|
||||
log_debug("\t\tAPI Socket Path: %s\n", app.app_api_socket_path.c_str());
|
||||
log_debug("\t\tServer Out IP: %s\n", app.app_server_out_ip.c_str());
|
||||
log_debug("\t\tApp Port In: %d\n", app.app_port_in);
|
||||
log_debug("\t\tApp Port Out: %d\n", app.app_port_out);
|
||||
|
||||
} catch (const runtime_error &e) {
|
||||
cerr << "Error: " << e.what() << endl;
|
||||
return 1;
|
||||
}
|
||||
|
||||
// TODO: Implement Cache
|
||||
// TAG: Because sometimes the parser doesnt have the name of the server because it started after the server init
|
||||
// we can cache it and reuse it to avoid NULL names in the DB
|
||||
|
||||
while (STOP_PROGRAM == false) {
|
||||
// Receive data from server
|
||||
ssize_t received = sock.receive_server(buffer, sizeof(buffer));
|
||||
|
||||
|
||||
if (received > 0) {
|
||||
map.update_buffer(buffer, static_cast<size_t>(received));
|
||||
switch (map.get_message_type()) {
|
||||
// DONE:
|
||||
case ACSP_VERSION: {
|
||||
log_warn("Received Version Again? (Probably server restart) Resending Update Request @ %ums\n", UPDATE_INTERVAL);
|
||||
|
||||
char request[516] = {0};
|
||||
request[0] = ACSP_REALTIMEPOS_INTERVAL;
|
||||
request[1] = UPDATE_INTERVAL;
|
||||
sock.send_server(request, sizeof(request));
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
// TODO:
|
||||
case ACSP_CAR_UPDATE: {
|
||||
// log_info("Received car update.\n");
|
||||
break;
|
||||
}
|
||||
|
||||
// TODO:
|
||||
case ACSP_NEW_SESSION: {
|
||||
log_info("New session started.\n");
|
||||
map.parse_new_session(track);
|
||||
if (map.is_ok()) {
|
||||
session_manager.on_new_session(track);
|
||||
} else {
|
||||
log_error("Failed to parse new session data.\n");
|
||||
}
|
||||
|
||||
// TESTING: Print track info
|
||||
log_info("Track Info:\n");
|
||||
log_info("\t\tServer Name: %s\n", track.server_name);
|
||||
log_info("\t\tTrack: %s\n", track.track);
|
||||
log_info("\t\tTrack Config: %s\n", track.track_config);
|
||||
log_info("\t\tSession Name: %s\n", track.session_name);
|
||||
log_info("\t\tWeather Graphics: %s\n", track.weather_graphics);
|
||||
log_info("\t\tSession Type: %d\n", track.session_type);
|
||||
log_info("\t\tLaps: %d\n", track.laps);
|
||||
log_info("\t\tTime: %d\n", track.time);
|
||||
log_info("\t\tAmbient Temp: %d\n", track.ambient_temp);
|
||||
log_info("\t\tRoad Temp: %d\n", track.road_temp);
|
||||
log_info("\t\tElapsed MS: %u\n", track.elapsed_ms);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
default: {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
delete[] track.server_name;
|
||||
delete[] track.track;
|
||||
delete[] track.track_config;
|
||||
delete[] track.session_name;
|
||||
delete[] track.weather_graphics;
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
#include "mapper.hpp"
|
||||
#include "parcer.h"
|
||||
|
||||
Mapper::Mapper(const uint8_t *buf, size_t size) : buffer(buf), buffer_size(size), offset(0), ok(1) {}
|
||||
|
||||
uint8_t Mapper::get_message_type() {
|
||||
if (buffer_size < 1) {
|
||||
this->ok = false;
|
||||
return 0;
|
||||
}
|
||||
|
||||
return buffer[0];
|
||||
}
|
||||
|
||||
void Mapper::parse_new_session(trackAtributes &track) {
|
||||
reset();
|
||||
int __ok;
|
||||
|
||||
track.protocol_version = read_uint8(buffer, buffer_size, &offset, &__ok);
|
||||
track.session_index = read_uint8(buffer, buffer_size, &offset, &__ok);
|
||||
track.current_session_index = read_uint8(buffer, buffer_size, &offset, &__ok);
|
||||
track.session_count = read_uint8(buffer, buffer_size, &offset, &__ok);
|
||||
|
||||
track.session_type = (SessionType)track.session_index;
|
||||
|
||||
uint8_t str_len = read_uint8(buffer, buffer_size, &offset, &__ok);
|
||||
read_utf32le_string(buffer, buffer_size, &offset, track.server_name, str_len, &__ok);
|
||||
|
||||
str_len = read_uint8(buffer, buffer_size, &offset, &__ok);
|
||||
read_string(buffer, buffer_size, &offset, track.track, str_len, &__ok);
|
||||
|
||||
str_len = read_uint8(buffer, buffer_size, &offset, &__ok);
|
||||
read_string(buffer, buffer_size, &offset, track.track_config, str_len, &__ok);
|
||||
|
||||
str_len = read_uint8(buffer, buffer_size, &offset, &__ok);
|
||||
read_string(buffer, buffer_size, &offset, track.session_name, str_len, &__ok);
|
||||
|
||||
track.typ = read_uint8(buffer, buffer_size, &offset, &__ok);
|
||||
track.time = read_uint16_le(buffer, buffer_size, &offset, &__ok);
|
||||
track.laps = read_uint16_le(buffer, buffer_size, &offset, &__ok);
|
||||
track.wait_time = read_uint16_le(buffer, buffer_size, &offset, &__ok);
|
||||
track.ambient_temp = read_uint8(buffer, buffer_size, &offset, &__ok);
|
||||
track.road_temp = read_uint8(buffer, buffer_size, &offset, &__ok);
|
||||
|
||||
str_len = read_uint8(buffer, buffer_size, &offset, &__ok);
|
||||
read_string(buffer, buffer_size, &offset, track.weather_graphics, str_len, &__ok);
|
||||
|
||||
track.elapsed_ms = read_uint32(buffer, buffer_size, &offset, &__ok);
|
||||
|
||||
if (__ok == 0) {
|
||||
this->ok = false;
|
||||
} else {
|
||||
this->ok = true;
|
||||
}
|
||||
}
|
||||
|
||||
-116
@@ -1,116 +0,0 @@
|
||||
#include "net.hpp"
|
||||
#include "log.c"
|
||||
#include <sys/types.h>
|
||||
|
||||
Socket::Socket() {
|
||||
sock_server = socket(AF_INET, SOCK_DGRAM, 0);
|
||||
sock_unix = -1;
|
||||
if (sock_server < 0) {
|
||||
throw runtime_error("Failed to create socket");
|
||||
}
|
||||
memset(&server_addr, 0, sizeof(server_addr));
|
||||
server_addr.sin_family = AF_INET;
|
||||
}
|
||||
|
||||
Socket::~Socket() {
|
||||
close(sock_server);
|
||||
close(sock_unix);
|
||||
}
|
||||
|
||||
void Socket::connect_server(const char *ip, uint16_t port) {
|
||||
this->server_port_input = port;
|
||||
server_addr.sin_port = htons(port);
|
||||
if (inet_pton(AF_INET, ip, &server_addr.sin_addr) <= 0) {
|
||||
throw runtime_error("Invalid IP address");
|
||||
}
|
||||
}
|
||||
|
||||
void Socket::bind_server(const char *ip, uint16_t port) {
|
||||
struct sockaddr_in bind_addr;
|
||||
memset(&bind_addr, 0, sizeof(bind_addr));
|
||||
bind_addr.sin_family = AF_INET;
|
||||
bind_addr.sin_port = htons(port);
|
||||
bind_addr.sin_addr.s_addr = inet_addr(ip);
|
||||
|
||||
if (bind(sock_server, (const struct sockaddr *)&bind_addr, sizeof(bind_addr)) < 0) {
|
||||
log_error("Failed to bind UDP socket on %s:%d\n", ip, port);
|
||||
throw runtime_error("Failed to bind UDP socket");
|
||||
}
|
||||
|
||||
log_info("Successfully bound UDP socket on %s:%d\n", ip, port);
|
||||
}
|
||||
|
||||
void Socket::connect_unix(const char *ip, uint16_t port) {
|
||||
sock_unix = socket(AF_UNIX, SOCK_STREAM, 0);
|
||||
if (sock_unix < 0) {
|
||||
throw std::runtime_error("Failed to create UNIX socket");
|
||||
}
|
||||
|
||||
this->server_addr_unix.sun_family = AF_UNIX;
|
||||
strncpy(this->server_addr_unix.sun_path, ip, sizeof(this->server_addr_unix.sun_path) - 1);
|
||||
|
||||
if (connect(sock_unix, (struct sockaddr *)&server_addr_unix, sizeof(server_addr_unix)) < 0) {
|
||||
throw std::runtime_error("Failed to connect to UNIX socket");
|
||||
}
|
||||
}
|
||||
|
||||
void Socket::send_server() {
|
||||
ssize_t sent_bytes = sendto(sock_server, &packet_data, sizeof(packet_data), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
|
||||
if (sent_bytes < 0) {
|
||||
throw runtime_error("Failed to send data");
|
||||
}
|
||||
}
|
||||
|
||||
ssize_t Socket::receive_server(void *buffer, size_t len) {
|
||||
ssize_t recv_bytes = recv(sock_server, buffer, len, 0);
|
||||
if (recv_bytes < 0) {
|
||||
log_error("Failed to receive data from server socket\n");
|
||||
return -1;
|
||||
}
|
||||
return recv_bytes;
|
||||
}
|
||||
|
||||
void Socket::send_unix() {
|
||||
ssize_t sent_bytes = send(sock_unix, &packet_data, sizeof(packet_data), 0);
|
||||
if (sent_bytes < 0) {
|
||||
throw runtime_error("Failed to send data to UNIX socket");
|
||||
}
|
||||
}
|
||||
|
||||
void Socket::send_server(const api_packet &data) {
|
||||
ssize_t sent_bytes = sendto(sock_server, &data, sizeof(data), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
|
||||
if (sent_bytes < 0) {
|
||||
throw runtime_error("Failed to send data");
|
||||
}
|
||||
}
|
||||
|
||||
void Socket::send_server(const void *data, size_t len) {
|
||||
ssize_t sent_bytes = sendto(sock_server, data, len, 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
|
||||
if (sent_bytes < 0) {
|
||||
throw runtime_error("Failed to send data");
|
||||
}
|
||||
}
|
||||
|
||||
void Socket::send_unix(const api_packet &data) {
|
||||
ssize_t sent_bytes = send(sock_unix, &data, sizeof(data), 0);
|
||||
if (sent_bytes < 0) {
|
||||
throw runtime_error("Failed to send data to UNIX socket");
|
||||
}
|
||||
}
|
||||
|
||||
void Socket::set_packet(const api_packet &data) {
|
||||
packet_data = data;
|
||||
}
|
||||
|
||||
api_packet Socket::create_packet(uint8_t tracker_id) {
|
||||
api_packet pkt;
|
||||
memset(&pkt, 0, sizeof(pkt));
|
||||
|
||||
pkt.message_type = 65; // Handshake message type
|
||||
pkt.tracker_id = tracker_id;
|
||||
return pkt;
|
||||
}
|
||||
|
||||
api_packet Socket::get_packet() {
|
||||
return packet_data;
|
||||
}
|
||||
-155
@@ -1,155 +0,0 @@
|
||||
#include "parcer.h"
|
||||
#include "server_structs.h"
|
||||
#include <arpa/inet.h>
|
||||
#include <netinet/in.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
int ensure(size_t recv_len, size_t offset, size_t need) {
|
||||
return (offset + need <= recv_len);
|
||||
}
|
||||
|
||||
u_int8_t read_uint8(const u_int8_t *buf, size_t recv_len, size_t *offset, int *ok) {
|
||||
if (!ensure(recv_len, *offset, sizeof(uint8_t))) {
|
||||
*ok = 0;
|
||||
return 0;
|
||||
}
|
||||
u_int8_t v;
|
||||
memcpy(&v, buf + *offset, sizeof(v));
|
||||
*offset += sizeof(v);
|
||||
return v;
|
||||
}
|
||||
|
||||
u_int16_t read_uint16(const u_int8_t *buf, size_t recv_len, size_t *offset, int *ok) {
|
||||
if (!ensure(recv_len, *offset, sizeof(uint16_t))) {
|
||||
*ok = 0;
|
||||
return 0;
|
||||
}
|
||||
u_int16_t v;
|
||||
memcpy(&v, buf + *offset, sizeof(v));
|
||||
*offset += sizeof(v);
|
||||
|
||||
return (u_int16_t)ntohs(v);
|
||||
}
|
||||
|
||||
u_int16_t read_uint16_le(const u_int8_t *buf, size_t recv_len, size_t *offset, int *ok) {
|
||||
if (!ensure(recv_len, *offset, sizeof(uint16_t))) {
|
||||
*ok = 0;
|
||||
return 0;
|
||||
}
|
||||
u_int16_t v;
|
||||
memcpy(&v, buf + *offset, sizeof(v));
|
||||
*offset += sizeof(v);
|
||||
|
||||
return v;
|
||||
}
|
||||
|
||||
u_int32_t read_uint32(const u_int8_t *buf, size_t recv_len, size_t *offset, int *ok) {
|
||||
if (!ensure(recv_len, *offset, sizeof(uint32_t))) {
|
||||
*ok = 0;
|
||||
return 0;
|
||||
}
|
||||
u_int32_t v;
|
||||
memcpy(&v, buf + *offset, sizeof(v));
|
||||
*offset += sizeof(v);
|
||||
return (u_int32_t)ntohl(v);
|
||||
}
|
||||
|
||||
int32_t read_int32(const u_int8_t *buf, size_t recv_len, size_t *offset, int *ok) {
|
||||
if (!ensure(recv_len, *offset, sizeof(int32_t))) {
|
||||
*ok = 0;
|
||||
return 0;
|
||||
}
|
||||
int32_t v;
|
||||
memcpy(&v, buf + *offset, sizeof(v));
|
||||
*offset += sizeof(v);
|
||||
return (int32_t)ntohl((u_int32_t)v);
|
||||
}
|
||||
|
||||
float read_float(const u_int8_t *buf, size_t recv_len, size_t *offset, int *ok) {
|
||||
if (!ensure(recv_len, *offset, sizeof(float))) {
|
||||
*ok = 0;
|
||||
return 0.0f;
|
||||
}
|
||||
u_int32_t v_int;
|
||||
memcpy(&v_int, buf + *offset, sizeof(v_int));
|
||||
*offset += sizeof(v_int);
|
||||
v_int = ntohl(v_int);
|
||||
float v_float;
|
||||
memcpy(&v_float, &v_int, sizeof(v_float));
|
||||
return v_float;
|
||||
}
|
||||
|
||||
void read_bytes(const u_int8_t *buf, size_t recv_len, size_t *offset, u_int8_t *out, size_t len, int *ok) {
|
||||
if (!ensure(recv_len, *offset, len)) {
|
||||
*ok = 0;
|
||||
return;
|
||||
}
|
||||
memcpy(out, buf + *offset, len);
|
||||
*offset += len;
|
||||
}
|
||||
|
||||
void read_utf32le_string(const uint8_t *buffer, size_t buf_size, size_t *offset, char *dest, size_t max_len, int *ok) {
|
||||
size_t i = *offset;
|
||||
size_t j = 0;
|
||||
|
||||
while (i + 3 < buf_size && j < max_len) {
|
||||
uint32_t codeunit = buffer[i] | (buffer[i + 1] << 8) | (buffer[i + 2] << 16) | (buffer[i + 3] << 24);
|
||||
|
||||
if (codeunit == 0) {
|
||||
i += 4; // termina a string
|
||||
break;
|
||||
}
|
||||
|
||||
if (codeunit < 0x80) {
|
||||
dest[j++] = (char)codeunit;
|
||||
} else {
|
||||
dest[j++] = '?'; // substitui caracteres fora de ASCII
|
||||
}
|
||||
|
||||
i += 4;
|
||||
}
|
||||
|
||||
dest[j] = '\0';
|
||||
*offset = i;
|
||||
*ok = 1;
|
||||
}
|
||||
|
||||
void read_utf16le_string(const uint8_t *buffer, size_t buf_size, size_t *offset, char *dest, size_t max_len, int *ok) {
|
||||
size_t i = *offset;
|
||||
size_t j = 0;
|
||||
|
||||
while (i + 1 < buf_size && j < max_len - 1) {
|
||||
uint16_t codeunit = buffer[i] | (buffer[i + 1] << 8);
|
||||
|
||||
if (codeunit == 0) {
|
||||
i += 2; // termina a string
|
||||
break;
|
||||
}
|
||||
|
||||
if (codeunit < 0x80) {
|
||||
dest[j++] = (char)codeunit;
|
||||
} else {
|
||||
dest[j++] = '?'; // substitui caracteres fora de ASCII
|
||||
}
|
||||
|
||||
i += 2;
|
||||
}
|
||||
|
||||
dest[j] = '\0';
|
||||
*offset = i;
|
||||
*ok = 1;
|
||||
}
|
||||
|
||||
void read_string(const u_int8_t *buf, size_t recv_len, size_t *offset, char *out, size_t len, int *ok) {
|
||||
if (!ensure(recv_len, *offset, len)) {
|
||||
*ok = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
for (size_t i = 0; i <= len; i++) {
|
||||
out[i] = (char)buf[*offset + i];
|
||||
}
|
||||
out[len] = '\0'; // Ensure null termination
|
||||
*offset += len;
|
||||
*ok = 1;
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
#include "session.hpp"
|
||||
|
||||
void SessionManager::on_new_session(const trackAtributes &track) {
|
||||
track_info = track;
|
||||
}
|
||||
|
||||
void SessionManager::on_player_connected(const carAtributes &car) {
|
||||
if (car.carID < MAX_PLAYERS) {
|
||||
players[car.carID] = car;
|
||||
players[car.carID].isConnected = 1;
|
||||
players[car.carID].isLoading = 1;
|
||||
connected_players++;
|
||||
}
|
||||
}
|
||||
|
||||
void SessionManager::on_player_finished_loading(u_int8_t car_id) {
|
||||
if (car_id < MAX_PLAYERS) {
|
||||
players[car_id].isLoading = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void SessionManager::on_player_disconnected(u_int8_t car_id) {
|
||||
if (car_id < MAX_PLAYERS) {
|
||||
memset(&players[car_id], 0, sizeof(carAtributes));
|
||||
connected_players--;
|
||||
}
|
||||
}
|
||||
|
||||
void SessionManager::on_car_update(const carAtributes &car) {
|
||||
if (car.carID < MAX_PLAYERS) {
|
||||
players[car.carID] = car;
|
||||
}
|
||||
}
|
||||
|
||||
void SessionManager::on_lap_completed(u_int8_t car_id, u_int32_t lap_time, u_int32_t cuts) {
|
||||
if (car_id < MAX_PLAYERS) {
|
||||
players[car_id].lap_time = lap_time;
|
||||
players[car_id].cuts += cuts;
|
||||
}
|
||||
}
|
||||
|
||||
void SessionManager::on_collision(u_int8_t car1, u_int8_t car2) {
|
||||
if (car1 < MAX_PLAYERS) {
|
||||
players[car1].contacts++;
|
||||
}
|
||||
if (car2 < MAX_PLAYERS) {
|
||||
players[car2].contacts++;
|
||||
}
|
||||
}
|
||||
|
||||
api_packet SessionManager::build_packet(u_int8_t message_type) {
|
||||
api_packet pkt;
|
||||
memset(&pkt, 0, sizeof(pkt));
|
||||
|
||||
pkt.message_type = message_type;
|
||||
pkt.tracker_id = server_id;
|
||||
pkt.connected_players = connected_players;
|
||||
|
||||
for (u_int8_t i = 0; i < MAX_PLAYERS; i++) {
|
||||
pkt.cars[i].carID = players[i].carID;
|
||||
pkt.cars[i].position = players[i].position;
|
||||
pkt.cars[i].velocity = players[i].velocity;
|
||||
pkt.cars[i].carGear = players[i].carGear;
|
||||
pkt.cars[i].carRPM = players[i].carRPM;
|
||||
pkt.cars[i].lap_time = players[i].lap_time;
|
||||
pkt.cars[i].cuts = players[i].cuts;
|
||||
pkt.cars[i].total_cuts = players[i].total_cuts;
|
||||
pkt.cars[i].total_cuts_alltime = players[i].total_cuts_alltime; // TAG: Kinda useless
|
||||
pkt.cars[i].total_laps_completed = players[i].total_laps_completed;
|
||||
pkt.cars[i].contacts = players[i].contacts;
|
||||
pkt.cars[i].total_contacts = players[i].total_contacts;
|
||||
|
||||
pkt.cars[i].current_flag = players[i].current_flag;
|
||||
pkt.cars[i].normalizedSplinePos = players[i].normalizedSplinePos;
|
||||
|
||||
pkt.cars[i].isConnected = players[i].isConnected;
|
||||
pkt.cars[i].isLoading = players[i].isLoading;
|
||||
|
||||
strncpy(pkt.cars[i].car_model, players[i].car_model, sizeof(pkt.cars[i].car_model));
|
||||
strncpy(pkt.cars[i].car_skin, players[i].car_skin, sizeof(pkt.cars[i].car_skin));
|
||||
strncpy(pkt.cars[i].driver_name, players[i].driver_name, sizeof(pkt.cars[i].driver_name));
|
||||
strncpy(pkt.cars[i].driver_team, players[i].driver_team, sizeof(pkt.cars[i].driver_team));
|
||||
strncpy(pkt.cars[i].driver_GUID, players[i].driver_GUID, sizeof(pkt.cars[i].driver_GUID));
|
||||
}
|
||||
|
||||
// TAG: Also kinda useless to send track protocol
|
||||
pkt.track_info.protocol_version = track_info.protocol_version;
|
||||
|
||||
pkt.track_info.session_index = track_info.session_index;
|
||||
pkt.track_info.current_session_index = track_info.current_session_index;
|
||||
pkt.track_info.session_count = track_info.session_count;
|
||||
pkt.track_info.session_type = track_info.session_type;
|
||||
|
||||
strncpy(pkt.track_info.server_name, track_info.server_name, sizeof(pkt.track_info.server_name));
|
||||
strncpy(pkt.track_info.track, track_info.track, sizeof(pkt.track_info.track));
|
||||
strncpy(pkt.track_info.track_config, track_info.track_config, sizeof(pkt.track_info.track_config));
|
||||
strncpy(pkt.track_info.session_name, track_info.session_name, sizeof(pkt.track_info.session_name));
|
||||
|
||||
pkt.track_info.typ = track_info.typ;
|
||||
pkt.track_info.time = track_info.time;
|
||||
pkt.track_info.laps = track_info.laps;
|
||||
pkt.track_info.wait_time = track_info.wait_time;
|
||||
pkt.track_info.ambient_temp = track_info.ambient_temp;
|
||||
pkt.track_info.road_temp = track_info.road_temp;
|
||||
|
||||
strncpy(pkt.track_info.weather_graphics, track_info.weather_graphics, sizeof(pkt.track_info.weather_graphics));
|
||||
|
||||
pkt.track_info.elapsed_ms = track_info.elapsed_ms;
|
||||
|
||||
return pkt;
|
||||
}
|
||||
|
||||
SessionManager::SessionManager(u_int8_t sid) : server_id(sid), connected_players(0) {
|
||||
memset(&track_info, 0, sizeof(trackAtributes));
|
||||
memset(players, 0, sizeof(players));
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
#include "socket.h"
|
||||
|
||||
// =========================
|
||||
// UDP SOCKET FUCNTIONS
|
||||
// =========================
|
||||
|
||||
// Create a UDP socket
|
||||
// @return: Socket file descriptor, or -1 on error
|
||||
int create_udp_socket(void) {
|
||||
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
|
||||
if (sockfd < 0) {
|
||||
perror("[!] socket() failed");
|
||||
return -1;
|
||||
}
|
||||
return sockfd;
|
||||
}
|
||||
|
||||
// Create a UDP socket and connect it to a specific IP and port
|
||||
// Used for sending data (no bind needed)
|
||||
// @param ip: Destination IP address as a string
|
||||
// @return: Socket file descriptor, or -1 on error
|
||||
int connect_udp_socket(const char *ip, uint16_t port) {
|
||||
int sockfd = create_udp_socket();
|
||||
if (sockfd < 0)
|
||||
return -1;
|
||||
|
||||
struct sockaddr_in servaddr;
|
||||
memset(&servaddr, 0, sizeof(servaddr));
|
||||
servaddr.sin_family = AF_INET;
|
||||
servaddr.sin_port = htons(port);
|
||||
servaddr.sin_addr.s_addr = inet_addr(ip);
|
||||
|
||||
if (connect(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
|
||||
perror("[!] connect() failed");
|
||||
close(sockfd);
|
||||
return -1;
|
||||
}
|
||||
|
||||
printf("[+] Connected UDP socket to %s:%d\n", ip, port);
|
||||
return sockfd;
|
||||
}
|
||||
|
||||
// Create and bind a UDP socket to a local IP and port
|
||||
// Used for listening for incoming data
|
||||
// @param ip: Local IP address to bind to
|
||||
// @param port: Local port to bind to
|
||||
// @return: Socket file descriptor, or -1 on error
|
||||
int create_bound_udp_socket(const char *ip, uint16_t port) {
|
||||
int sockfd = create_udp_socket();
|
||||
if (sockfd < 0)
|
||||
return -1;
|
||||
|
||||
struct sockaddr_in addr;
|
||||
memset(&addr, 0, sizeof(addr));
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_port = htons(port);
|
||||
addr.sin_addr.s_addr = inet_addr(ip);
|
||||
|
||||
if (bind(sockfd, (const struct sockaddr *)&addr, sizeof(addr)) < 0) {
|
||||
perror("[!] bind() failed");
|
||||
close(sockfd);
|
||||
return -1;
|
||||
}
|
||||
|
||||
printf("[+] Bound UDP socket on %s:%d\n", ip, port);
|
||||
return sockfd;
|
||||
}
|
||||
|
||||
// Send a UDP message to the specified IP and port
|
||||
// @param sockfd: Socket file descriptor
|
||||
// @param message: Message to send
|
||||
// @param dest_ip: Destination IP address as a string
|
||||
// @param dest_port: Destination port
|
||||
// @return: Number of bytes sent, or -1 on error
|
||||
ssize_t send_udp_message(int sockfd, const char *message, const char *dest_ip, uint16_t dest_port) {
|
||||
struct sockaddr_in destaddr;
|
||||
memset(&destaddr, 0, sizeof(destaddr));
|
||||
destaddr.sin_family = AF_INET;
|
||||
destaddr.sin_port = htons(dest_port);
|
||||
destaddr.sin_addr.s_addr = inet_addr(dest_ip);
|
||||
|
||||
ssize_t n = sendto(sockfd, message, strlen(message), 0, (const struct sockaddr *)&destaddr, sizeof(destaddr));
|
||||
if (n < 0) {
|
||||
perror("[!] sendto() failed");
|
||||
return -1;
|
||||
}
|
||||
|
||||
printf("[+] Sent %zd bytes to %s:%d\n", n, dest_ip, dest_port);
|
||||
return n;
|
||||
}
|
||||
Reference in New Issue
Block a user