Compare commits

..

No commits in common. "stable" and "release" have entirely different histories.

44 changed files with 375 additions and 3382 deletions

View File

@ -1,53 +0,0 @@
# This is part of WHY2
# Copyright (C) 2022 Václav Šmejkal
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
name: Codacy Scan
on:
push:
branches: [ "development" ]
schedule:
- cron: '40 22 12 4 2'
permissions:
contents: read
jobs:
codacy-security-scan:
permissions:
contents: read
security-events: write
actions: read
name: Codacy Security Scan
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Run Codacy Analysis
uses: codacy/codacy-analysis-cli-action@d840f886c4bd4edc059706d09c6a1586111c540b
with:
project-token: ${{ secrets.CODACY_PROJECT_TOKEN }}
verbose: true
output: results.sarif
format: sarif
gh-code-scanning-compat: true
max-allowed-issues: 2147483647
- name: Upload results file
uses: github/codeql-action/upload-sarif@v2
with:
sarif_file: results.sarif

View File

@ -1,73 +0,0 @@
# This is part of WHY2
# Copyright (C) 2022 Václav Šmejkal
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
name: Build WHY2-chat
on:
push:
branches: [ development ]
workflow_dispatch:
schedule:
- cron: '40 22 12 4 2'
jobs:
test-why2:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ ubuntu-latest ]
include:
- os: ubuntu-latest
client: ./out/why2-chat-client
server: ./out/why2-chat-server
configure: configure.sh
steps:
- name: Checkout repository
uses: actions/checkout@v2
with:
ref: development
- if: matrix.os == 'ubuntu-latest'
name: Update packages
run: |
sudo apt update
# sudo apt upgrade
- name: Permissions
run: chmod +x ${{ matrix.configure }}
- name: Preparation
run: sudo ./${{ matrix.configure }}
- name: Install WHY2
run: make install
- name: Build Chat
run: make build_chat
- name: Upload Client
uses: actions/upload-artifact@v4
with:
name: WHY2 Chat Client
path: ${{ matrix.client }}
- name: Upload Server
uses: actions/upload-artifact@v4
with:
name: WHY2 Chat Server
path: ${{ matrix.server }}

View File

@ -59,10 +59,10 @@ jobs:
run: sudo apt install valgrind run: sudo apt install valgrind
- name: Install WHY2 - name: Install WHY2
run: make install run: sudo make install
- name: Build WHY2 Test - name: Build WHY2 Test
run: make test_core run: make testCore
- name: Test Lib - name: Test Lib
run: ./${{ matrix.output }} run: ./${{ matrix.output }}

View File

@ -59,10 +59,10 @@ jobs:
run: sudo apt install valgrind run: sudo apt install valgrind
- name: Install WHY2 - name: Install WHY2
run: make install run: sudo make install
- name: Build WHY2 Test - name: Build WHY2 Test
run: make test_logger run: make testLogger
- name: Test Lib - name: Test Lib
run: ./${{ matrix.output }} run: ./${{ matrix.output }}

View File

@ -53,7 +53,7 @@ jobs:
run: sudo ./${{ matrix.configure }} run: sudo ./${{ matrix.configure }}
- name: Install WHY2 - name: Install WHY2
run: make install run: sudo make install
- name: Download WHY2 test project - name: Download WHY2 test project
run: curl -Lo ${{ matrix.test }}.c https://gist.github.com/ENGO150/d8419b6c31ffb68ebb930a5b41af8c73/raw run: curl -Lo ${{ matrix.test }}.c https://gist.github.com/ENGO150/d8419b6c31ffb68ebb930a5b41af8c73/raw

4
.gitignore vendored
View File

@ -3,6 +3,4 @@
out/ out/
misc/ misc/
logs/ logs/
vgcore.* vgcore.*
target/
Cargo.lock

View File

@ -1,80 +0,0 @@
# This is part of WHY2
# Copyright (C) 2022 Václav Šmejkal
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
variables:
CLIENT: "./out/why2-chat-client"
SERVER: "./out/why2-chat-server"
CORE_OUTPUT: "./out/why2-core-test"
CORE_APP: "why2"
LOGGER_OUTPUT: "./out/why2-logger-test"
LOGGER_APP: "why2-logger"
VALGRIND: "valgrind --leak-check=full --show-leak-kinds=reachable --track-origins=yes -s"
why2-chat-build:
stage: build
image: rust:latest # Fixes cargo installation problems in ./configure.sh
script:
- apt update # Update repos
- apt install sudo lsb-release -y # Install needed stuff
- chmod +x configure.sh # Permissions
- sudo ./configure.sh # Preparation
- make install BYPASS_CHECK=true # Install WHY2
- make build_chat # Build Chat
artifacts:
paths:
- $CLIENT
- $SERVER
why2-core-test:
stage: build
image: rust:latest
script:
- apt update # Update repos
- apt install sudo lsb-release valgrind -y # Install needed stuff
- chmod +x configure.sh # Permissions
- sudo ./configure.sh # Preparation
- make install BYPASS_CHECK=true # Install WHY2
- make test_core # Build WHY2 Test
- ./$CORE_OUTPUT # Test Lib
- $CORE_APP # Test App
- $VALGRIND $CORE_OUTPUT # Test Lib by Valgrind
why2-logger-test:
stage: build
image: rust:latest
script:
- apt update # Update repos
- apt install sudo lsb-release valgrind -y # Install needed stuff
- chmod +x configure.sh # Permissions
- sudo ./configure.sh # Preparation
- make install BYPASS_CHECK=true # Install WHY2
- make test_logger # Build WHY2 Test
- ./$LOGGER_OUTPUT # Test Lib
- $LOGGER_APP # Test App
- $VALGRIND $LOGGER_OUTPUT # Test Lib by Valgrind
why2-project:
stage: build
image: rust:latest
script:
- apt update # Update repos
- apt install sudo lsb-release -y # Install needed stuff
- chmod +x configure.sh # Permissions
- sudo ./configure.sh # Preparation
- make install BYPASS_CHECK=true # Install WHY2
- curl -Lo test.c https://gist.github.com/ENGO150/d8419b6c31ffb68ebb930a5b41af8c73/raw # Download WHY2 test project
- cc test.c -lwhy2 -Wall -o test # Build WHY2 project
- ./test # Run Test

View File

@ -1,5 +0,0 @@
- https://github.com/ENGO150/WHY2
- https://gitlab.com/ENGO150/why2
- https://gitlab.spseplzen.cz/smejkalv/why2
Contact me for access to private mirror.

View File

@ -16,9 +16,6 @@
# Compiler Settings # Compiler Settings
CC=cc CC=cc
RC=cargo
CP=sudo install -m 755 # Not so compiler related but idk where to put it
RFLAGS=--manifest-path src/chat/config/Cargo.toml
CFLAGS=-Wall -Wextra -Werror -Wcomment -Wformat -Wformat-security -Wmain -Wnonnull -Wunused -std=gnu11 -O2 -g # Remove the '-g' flag if you want the smallest possible lib size CFLAGS=-Wall -Wextra -Werror -Wcomment -Wformat -Wformat-security -Wmain -Wnonnull -Wunused -std=gnu11 -O2 -g # Remove the '-g' flag if you want the smallest possible lib size
# Output Files # Output Files
@ -32,24 +29,15 @@ OUTPUT_APP_CORE=$(OUTPUT)/$(PROJECT_NAME)-core-app
OUTPUT_TEST_LOGGER=$(OUTPUT)/$(PROJECT_NAME)-logger-test OUTPUT_TEST_LOGGER=$(OUTPUT)/$(PROJECT_NAME)-logger-test
OUTPUT_APP_LOGGER=$(OUTPUT)/$(PROJECT_NAME)-logger-app OUTPUT_APP_LOGGER=$(OUTPUT)/$(PROJECT_NAME)-logger-app
OUTPUT_CHAT_CLIENT=$(OUTPUT)/$(PROJECT_NAME)-chat-client
OUTPUT_CHAT_SERVER=$(OUTPUT)/$(PROJECT_NAME)-chat-server
LIB_CHAT_CONFIG_OUT=./src/chat/config/target/release
# Source Code # Source Code
SRC_CORE=./src/core/lib/*.c ./src/core/lib/utils/*.c SRC_CORE=./src/core/lib/*.c ./src/core/lib/utils/*.c
SRC_CORE_APP=./src/core/app/*.c SRC_CORE_APP=./src/core/app/*.c
SRC_LOGGER=./src/logger/lib/*.c SRC_LOGGER=./src/logger/lib/*.c
SRC_LOGGER_APP=./src/logger/app/*.c SRC_LOGGER_APP=./src/logger/app/*.c
SRC_CHAT_CLIENT=./src/chat/main/client.c
SRC_CHAT_SERVER=./src/chat/main/server.c
SRC_CHAT_MISC=./src/chat/*.c
INCLUDE_DIR=./include INCLUDE_DIR=./include
INCLUDE_CORE=$(INCLUDE_DIR)/*.h INCLUDE_CORE=$(INCLUDE_DIR)/*.h
INCLUDE_LOGGER=$(INCLUDE_DIR)/logger/*.h INCLUDE_LOGGER=$(INCLUDE_DIR)/logger/*.h
INCLUDE_CHAT=$(INCLUDE_DIR)/chat/*.h
TEST_CORE=./src/core/lib/test/main.c TEST_CORE=./src/core/lib/test/main.c
LIBS_CORE=-ljson-c -lcurl -lgit2 LIBS_CORE=-ljson-c -lcurl -lgit2
@ -59,11 +47,6 @@ TEST_LOGGER=./src/logger/lib/test/main.c
LIBS_LOGGER=$(LIB_CORE) LIBS_LOGGER=$(LIB_CORE)
LIB_LOGGER=-l$(PROJECT_NAME)-logger LIB_LOGGER=-l$(PROJECT_NAME)-logger
LIBS_LIB_CHAT=$(LIB_CORE) -lpthread -lgmp
LIB_CHAT=-l$(PROJECT_NAME)-chat
LIB_CHAT_CONFIG=$(LIB_CHAT)-config
LIBS_CHAT=$(LIB_CHAT) $(LIBS_LIB_CHAT) $(LIB_CHAT_CONFIG)
# Install Files # Install Files
INSTALL_INCLUDE=/usr/include INSTALL_INCLUDE=/usr/include
INSTALL_LIBRARY=/usr/lib INSTALL_LIBRARY=/usr/lib
@ -74,86 +57,56 @@ DOLLAR=$
########## ##########
no_target: # Do not use this, please <3 noTarget: # Do not use this, please <3
@echo Hey you... You have to enter your target, too. Use \'install\' target for installing $(PROJECT_NAME)-core. @echo Hey you... You have to enter your target, too. Use \'install\' target for installing $(PROJECT_NAME)-core.
check_root: installHeaderCore:
ifneq ($(BYPASS_CHECK),true) for file in $(INCLUDE_CORE); do install -m 755 -D $(DOLLAR)file -t $(INSTALL_INCLUDE)/$(PROJECT_NAME); done
@if [ "$(shell id -u)" = 0 ]; then\ ln -sf $(INSTALL_INCLUDE)/$(PROJECT_NAME)/$(PROJECT_NAME).h $(INSTALL_INCLUDE)/$(PROJECT_NAME).h
echo "Do not run install rules as root.";\
exit 1;\
fi
endif
install_header_core: installHeaderLogger:
for file in $(INCLUDE_CORE); do $(CP) -D $(DOLLAR)file -t $(INSTALL_INCLUDE)/$(PROJECT_NAME); done for file in $(INCLUDE_LOGGER); do install -m 755 -D $(DOLLAR)file -t $(INSTALL_INCLUDE)/$(PROJECT_NAME)/logger; done
sudo ln -sf $(INSTALL_INCLUDE)/$(PROJECT_NAME)/$(PROJECT_NAME).h $(INSTALL_INCLUDE)/$(PROJECT_NAME).h
install_header_logger: buildLibCore:
for file in $(INCLUDE_LOGGER); do $(CP) -D $(DOLLAR)file -t $(INSTALL_INCLUDE)/$(PROJECT_NAME)/logger; done
install_header_chat:
for file in $(INCLUDE_CHAT); do $(CP) -D $(DOLLAR)file -t $(INSTALL_INCLUDE)/$(PROJECT_NAME)/chat; done
build_lib_core:
$(MAKE) clean $(MAKE) clean
$(CC) $(CFLAGS) -fPIC -c $(SRC_CORE) $(CC) $(CFLAGS) -fPIC -c $(SRC_CORE)
$(CC) $(CFLAGS) -shared -o lib$(PROJECT_NAME).so *.o $(LIBS_CORE) $(CC) $(CFLAGS) -shared -o lib$(PROJECT_NAME).so *.o $(LIBS_CORE)
build_lib_logger: buildLibLogger:
$(MAKE) clean $(MAKE) clean
$(CC) $(CFLAGS) -fPIC -c $(SRC_LOGGER) $(CC) $(CFLAGS) -fPIC -c $(SRC_LOGGER)
$(CC) $(CFLAGS) -shared -o lib$(PROJECT_NAME)-logger.so *.o $(LIBS_LOGGER) $(CC) $(CFLAGS) -shared -o lib$(PROJECT_NAME)-logger.so *.o $(LIBS_LOGGER)
build_chat_client: installLibCore: buildLibCore
$(CC) $(CFLAGS) $(SRC_CHAT_CLIENT) -o $(OUTPUT_CHAT_CLIENT) $(LIBS_CHAT) install -m 755 ./lib$(PROJECT_NAME).so $(INSTALL_LIBRARY)/lib$(PROJECT_NAME).so
build_chat_server: installAppCore: appCore
$(CC) $(CFLAGS) $(SRC_CHAT_SERVER) -o $(OUTPUT_CHAT_SERVER) $(LIBS_CHAT) install -m 755 $(OUTPUT_APP_CORE) $(INSTALL_BIN)/$(PROJECT_NAME)
build_lib_chat: installLibLogger: buildLibLogger
$(MAKE) clean install -m 755 ./lib$(PROJECT_NAME)-logger.so $(INSTALL_LIBRARY)/lib$(PROJECT_NAME)-logger.so
$(CC) $(CFLAGS) -fPIC -c $(SRC_CHAT_MISC)
$(RC) build $(RFLAGS) --release
$(CP) $(LIB_CHAT_CONFIG_OUT)/lib$(PROJECT_NAME)_chat_config.so $(INSTALL_LIBRARY)/lib$(PROJECT_NAME)-chat-config.so
$(CC) $(CFLAGS) -shared -o lib$(PROJECT_NAME)-chat.so *.o $(LIBS_LIB_CHAT)
install_lib_core: build_lib_core installAppLogger: appLogger
$(CP) ./lib$(PROJECT_NAME).so $(INSTALL_LIBRARY)/lib$(PROJECT_NAME).so install -m 755 $(OUTPUT_APP_LOGGER) $(INSTALL_BIN)/$(PROJECT_NAME)-logger
install_app_core: app_core testCore:
$(CP) $(OUTPUT_APP_CORE) $(INSTALL_BIN)/$(PROJECT_NAME)
install_lib_logger: build_lib_logger
$(CP) ./lib$(PROJECT_NAME)-logger.so $(INSTALL_LIBRARY)/lib$(PROJECT_NAME)-logger.so
install_app_logger: app_logger
$(CP) $(OUTPUT_APP_LOGGER) $(INSTALL_BIN)/$(PROJECT_NAME)-logger
install_lib_chat: build_lib_chat
$(CP) ./lib$(PROJECT_NAME)-chat.so $(INSTALL_LIBRARY)/lib$(PROJECT_NAME)-chat.so
test_core:
$(CC) $(CFLAGS) $(TEST_CORE) -o $(OUTPUT_TEST_CORE) $(LIB_CORE) $(CC) $(CFLAGS) $(TEST_CORE) -o $(OUTPUT_TEST_CORE) $(LIB_CORE)
test_logger: testLogger:
$(CC) $(CFLAGS) $(TEST_LOGGER) -o $(OUTPUT_TEST_LOGGER) $(LIBS_LOGGER) $(LIB_LOGGER) $(CC) $(CFLAGS) $(TEST_LOGGER) -o $(OUTPUT_TEST_LOGGER) $(LIBS_LOGGER) $(LIB_LOGGER)
app_core: appCore:
$(CC) $(CFLAGS) $(SRC_CORE_APP) -o $(OUTPUT_APP_CORE) $(LIB_CORE) $(CC) $(CFLAGS) $(SRC_CORE_APP) -o $(OUTPUT_APP_CORE) $(LIB_CORE)
app_logger: appLogger:
$(CC) $(CFLAGS) $(SRC_LOGGER_APP) -o $(OUTPUT_APP_LOGGER) $(LIBS_LOGGER) $(LIB_LOGGER) $(CC) $(CFLAGS) $(SRC_LOGGER_APP) -o $(OUTPUT_APP_LOGGER) $(LIBS_LOGGER) $(LIB_LOGGER)
clean: clean:
$(RC) clean $(RFLAGS)
rm -rf $(OUTPUT)/* $(LOGS)/* *.o *.so vgcore.* rm -rf $(OUTPUT)/* $(LOGS)/* *.o *.so vgcore.*
build_chat: build_chat_server build_chat_client installHeader: installHeaderCore installHeaderLogger
installLibs: installLibCore installLibLogger
install_header: install_header_core install_header_logger install_header_chat installApps: installAppCore installAppLogger
install_libs: install_lib_core install_lib_logger install_lib_chat install: installHeader installLibs installApps clean
install_apps: install_app_core install_app_logger installTest: install testCore testLogger
install: check_root install_header install_libs install_apps clean
install_test: install test_core test_logger
all: install all: install

37
configure.sh Executable file → Normal file
View File

@ -24,43 +24,16 @@ if [[ $(id -u) != "0" ]] && [[ $1 != "force" ]]; then
exit 1 exit 1
fi fi
COMMON="gcc make tmux curl"
ARCH_GENTOO_COMMON="$COMMON json-c libgit2 gmp"
# Get COMMAND # Get COMMAND
if [[ $DISTRO == "Arch" ]]; then if [[ $DISTRO == "Arch" ]]; then
COMMAND="pacman -S --needed --noconfirm $ARCH_GENTOO_COMMON" COMMAND="pacman -S --needed --noconfirm gcc json-c curl make libgit2 tmux"
elif [[ $DISTRO == "Ubuntu" ]] || [[ $DISTRO == "Debian" ]]; then elif [[ $DISTRO == "Ubuntu" ]] || [[ $DISTRO == "Debian" ]]; then
COMMAND="apt install -y $COMMON libjson-c-dev libcurl4-nss-dev libgit2-dev libgmp-dev" COMMAND="apt install -y gcc libjson-c-dev libcurl4-nss-dev make libgit2-dev tmux"
elif [[ $DISTRO == "Gentoo" ]]; then else
COMMAND="emerge -vn $ARCH_GENTOO_COMMON" # 'Unsupported' distro
echo "It seems you are using unsupported distribution... Don't worry, just install 'gcc', 'json-c', 'curl', 'libgit2', 'tmux' and 'make' and you'll be fine."
# Add
echo "LDPATH=/usr/lib/libwhy2.so" > /etc/env.d/99why2-core
echo "LDPATH=/usr/lib/libwhy2-logger.so" > /etc/env.d/99why2-logger
echo "LDPATH=/usr/lib/libwhy2-chat.so" > /etc/env.d/99why2-chat
echo "LDPATH=/usr/lib/libwhy2-chat-config.so" > /etc/env.d/99why2-chat-config
env-update && source /etc/profile
else # 'Unsupported' distro
IFS=' ' read -r -a dependency_array <<< "$ARCH_GENTOO_COMMON" # Split into dependency_array
echo -e "It seems you are using unsupported distribution...\nDon't worry, just install these dependencies:\n"
for dependency in "${dependency_array[@]}" # Iter
do
echo "$dependency"
done
echo -e "\nand you'll be fine."
exit exit
fi fi
# Execute COMMAND # Execute COMMAND
$COMMAND $COMMAND
# Install Rust
if ! [ -x "$(command -v cargo)" ]; then
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y # Install Rust and components
source "$HOME/.cargo/env"
fi

View File

@ -1,49 +0,0 @@
/*
This is part of WHY2
Copyright (C) 2022 Václav Šmejkal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef WHY2_CHAT_CONFIG_H
#define WHY2_CHAT_CONFIG_H
#ifdef __cplusplus
extern "C" {
#endif
#include <why2/flags.h> //damn i really hate including headers in headers
//CONFIG MACROS
#define WHY2_CHAT_CONFIG_URL "https://raw.githubusercontent.com/ENGO150/WHY2/development/src/chat/config/"
#define WHY2_CHAT_CONFIG_SERVER "server.toml"
#define WHY2_CHAT_CONFIG_CLIENT "client.toml"
#define WHY2_CHAT_CONFIG_SERVER_USERS "server_users.toml" //LOGIN INFO CONFIG
void why2_chat_init_server_config(void); //CHECK IF SERVER CONFIG EXISTS, CREATE IT
void why2_chat_init_client_config(void); //Dementia is a term used to describe a group of symptoms affecting memory, thinking and social abilities. In people who have dementia, the symptoms interfere with their daily lives. Dementia isn't one specific disease. Several diseases can cause dementia. ...
char *why2_toml_read(const char* path, const char* key); //READ key FROM path TOML FILE
void why2_toml_write(const char *path, const char *key, const char *value); //WRITE value AS key INTO path TOML FILE
why2_bool why2_toml_contains(const char *path, const char *key); //CHECK IF path CONTAINS key
void why2_toml_read_free(char* s); //DEALLOCATE THE READ VALUE
char *why2_chat_server_config(char *key); //why2_toml_read BUT YOU DO NOT HAVE TO INCLUDE path
char *why2_chat_client_config(char *key); //hihi, *grabs shotgun quietly*
#ifdef __cplusplus
}
#endif
#endif

View File

@ -1,51 +0,0 @@
/*
This is part of WHY2
Copyright (C) 2022 Václav Šmejkal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef WHY2_CHAT_CRYPTO_H
#define WHY2_CHAT_CRYPTO_H
#ifdef __cplusplus
extern "C" {
#endif
#include <why2/chat/config.h>
//MACROS
#define WHY2_CHAT_KEY_BITS 4096 //BITS..
#define WHY2_CHAT_PRIME_ITERS 100 //NUMBER OF ITERATIONS WHEN CHECKING PRIME NUMBER
#define WHY2_CHAT_RSA_EXPONENT "H33" //DEFAULT e IN BASE WHY2_CHAT_KEY_BASE
#define WHY2_CHAT_KEY_LOCATION WHY2_CONFIG_DIR "/keys" //KEYS LOCATION
#define WHY2_CHAT_PUB_KEY "pub"
#define WHY2_CHAT_PRI_KEY "pri"
#define WHY2_CHAT_KEY_BASE 62 //BASE IN THE GENERATED KEYS ARE STORED IN WHY2_CHAT_KEY_LOCATION
void why2_chat_init_keys(void); //INIT (POSSIBLY GENERATE) RSA KEYS
void why2_chat_deallocate_keys(void); //DEALLOCATE :) (NO SLUR HERE)
char *why2_get_chat_modulus(void); //GET THE RSA MODULUS
char *why2_get_chat_d(void); //GET THE RSA d
char *why2_chat_rsa_pub_encrypt(char *to_encrypt); //RSA ENCRYPT USING PUBLIC KEY
char *why2_chat_rsa_pri_decrypt(char *to_decrypt); //RSA DECRYPT USING PRIVATE KEY
#ifdef __cplusplus
}
#endif
#endif

View File

@ -1,68 +0,0 @@
/*
This is part of WHY2
Copyright (C) 2022 Václav Šmejkal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef WHY2_CHAT_COMMON_H
#define WHY2_CHAT_COMMON_H
#ifdef __cplusplus
extern "C" {
#endif
//MACROS
#define WHY2_SA struct sockaddr
#define WHY2_CHAT_SERVER_PORT 1204 //PORT
#define WHY2_MAX_CONNECTIONS 1000 //MAX USERS CONNECTED AT ONE TIME
#define WHY2_CLEAR_AND_GO_UP "\33[2K\r\033[A" //i mean read the name
#define WHY2_INVALID_POINTER (void*) 0xffffffffffffffff
//(SERVER -> CLIENT) CODES
#define WHY2_CHAT_CODE_ACCEPT_MESSAGES "code_000" //TELL CLIENT THEY CAN SEND MESSAGES
#define WHY2_CHAT_CODE_PICK_USERNAME "code_001" //TELL CLIENT TO PICK USERNAME
#define WHY2_CHAT_CODE_SERVER_SIDE_QUIT_COMMUNICATION "code_002" //TELL CLIENT TO END COMMUNICATION (just so they don't get segfault on server-side disconnect)
#define WHY2_CHAT_CODE_INVALID_USERNAME "code_003" //haha
#define WHY2_CHAT_CODE_LIST_SERVER "code_004" //SAME AS WHY2_CHAT_CODE_LIST BUT BACK TO THE CLIENT
#define WHY2_CHAT_CODE_VERSION_SERVER "code_005" //SAME AS WHY2_CHAT_CODE_VERSION BUT BACK TO THE CLIENT
#define WHY2_CHAT_CODE_PM_SERVER "code_006" //SAME AS WHY2_CHAT_CODE_PM BUT BACK TO THE CLIENT
//(CLIENT -> SERVER) CODES
#define WHY2_CHAT_CODE_EXIT "code_999" //TELL SERVER YOU ARE ENDING COMMUNICATION
#define WHY2_CHAT_CODE_LIST "code_998" //TELL SERVER TO GIVE YOU ALL CONNECTED USERS
#define WHY2_CHAT_CODE_PM "code_997" //TELL SERVER TO SEND MESSAGE ONLY TO SPECIFIC ID
#define WHY2_CHAT_CODE_VERSION "code_996" //TELL SERVER TO GIVE YOU ITS VERSION
//COMMANDS
#define WHY2_CHAT_COMMAND_PREFIX "!" //the little thingy you write before the command names to make the program recognise them boy. You know? Like in minecraft you use /kill... Also, are you dumb?
#define WHY2_CHAT_COMMAND_EXIT "exit" //QUIT THE PROGRAM CMD
#define WHY2_CHAT_COMMAND_HELP "help" //PRINT ALL COMMANDS
#define WHY2_CHAT_COMMAND_LIST "list" //LIST ALL CONNECTIONS
#define WHY2_CHAT_COMMAND_PM "pm" //PRIVATE MESSAGES
#define WHY2_CHAT_COMMAND_VERSION "version" //COMPARE CLIENT VERSION AND SERVER VERSION
//SHORTCUTS CAUSE I'M LAZY BITCH
#define WHY2_CHAT_CODE_SSQC WHY2_CHAT_CODE_SERVER_SIDE_QUIT_COMMUNICATION
char *why2_chat_client_get_server_exit_cmd(); //GETTER AND SETTER FOR !exit FROM SERVER
void why2_chat_client_set_server_exit_cmd(char *cmd);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -1,41 +0,0 @@
/*
This is part of WHY2
Copyright (C) 2022 Václav Šmejkal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef WHY2_CHAT_MISC_H
#define WHY2_CHAT_MISC_H
#ifdef __cplusplus
extern "C" {
#endif
#include <why2/flags.h> //TODO: fuck this
void why2_send_socket(char *text, char *username, int socket); //send socket.... wtf did you expect
void *why2_communicate_thread(void *arg); //COMMUNICATION THREAD
void *why2_accept_thread(void *socket); //LOOP ACCEPTING CONNECTIONS
void why2_clean_connections(void); //CLOSE EVERY CONNECTION
void why2_clean_threads(void); //CLOSE EVERY RUNNING MESSAGE THREAD
void *why2_listen_server(void *socket); //LISTEN FOR OTHER's USERS MESSAGES
void *why2_getline_thread(WHY2_UNUSED void* arg); //START getline IN SEPARATE THREAD
void why2_trim_string(char **s); //REMOVES SPACES FROM END AND START OF *s
#ifdef __cplusplus
}
#endif
#endif

View File

@ -19,16 +19,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef WHY2_DECRYPTER_H #ifndef WHY2_DECRYPTER_H
#define WHY2_DECRYPTER_H #define WHY2_DECRYPTER_H
#ifdef __cplusplus
extern "C" {
#endif
#include <why2/flags.h> #include <why2/flags.h>
why2_output_flags why2_decrypt_text(char *text, char *key_new); //TEXT from WILL BE DECRYPTED WITH KEY AND RETURNED why2_output_flags why2_decrypt_text(char *text, char *keyNew); //TEXT from WILL BE DECRYPTED WITH KEY AND RETURNED
#ifdef __cplusplus
}
#endif
#endif #endif

View File

@ -19,16 +19,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef WHY2_ENCRYPTER_H #ifndef WHY2_ENCRYPTER_H
#define WHY2_ENCRYPTER_H #define WHY2_ENCRYPTER_H
#ifdef __cplusplus
extern "C" {
#endif
#include <why2/flags.h> #include <why2/flags.h>
why2_output_flags why2_encrypt_text(char *text, char *key_new); //TEXT from WILL BE ENCRYPTED WITH KEY AND RETURNED why2_output_flags why2_encrypt_text(char *text, char *keyNew); //TEXT from WILL BE ENCRYPTED WITH KEY AND RETURNED
#ifdef __cplusplus
}
#endif
#endif #endif

View File

@ -19,10 +19,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef WHY2_FLAGS_H #ifndef WHY2_FLAGS_H
#define WHY2_FLAGS_H #define WHY2_FLAGS_H
#ifdef __cplusplus
extern "C" {
#endif
//CONSTS //CONSTS
enum WHY2_EXIT_CODES //exit codes you fucking idiot enum WHY2_EXIT_CODES //exit codes you fucking idiot
{ {
@ -33,25 +29,9 @@ enum WHY2_EXIT_CODES //exit codes you fucking idiot
WHY2_WHY2_UPDATE_FAILED = 3 //EXIT VALUE FOR UPDATE FAILED WHY2_WHY2_UPDATE_FAILED = 3 //EXIT VALUE FOR UPDATE FAILED
}; };
//THESE ARE 'HISTORIC' VERSION FOR GENERATING tkch, SO YOU CAN DECRYPT OLD TEXT
enum WHY2_TEXT_KEY_CHAIN_VERSIONS
{
WHY2_v1, //FIRST VERSION. Replaced on May 28th 17:45:26 2022 UTC in commit 0d64f4fa7c37f0b57914db902258e279a71c7f9a.
WHY2_v2, //SECOND VERSION. Replaced on July 11th 17:12:41 2022 UTC in commit 0f01cde0f1e1a9210f4eef7b949e6d247072d3a6.
WHY2_v3 //THIRD VERSION. THE LATEST ONE
};
enum WHY2_OUTPUT_FORMAT
{
WHY2_OUTPUT_TEXT,
WHY2_OUTPUT_BYTE
};
#define WHY2_VERSION "v5.0" //WHY2_VERSION OF CURRENT BUILD > DO NOT TOUCH THIS < #define WHY2_VERSION "v5.0" //WHY2_VERSION OF CURRENT BUILD > DO NOT TOUCH THIS <
#define WHY2_VERSIONS_URL "https://raw.githubusercontent.com/ENGO150/WHY2/release/versions.json" //URL FOR GETTING versions.json #define WHY2_VERSIONS_URL "https://raw.githubusercontent.com/ENGO150/WHY2/release/versions.json" //URL FOR GETTING versions.json
#define WHY2_CONFIG_DIR "/home/{USER}/.config/WHY2" #define WHY2_VERSIONS_NAME "/tmp/why2-versions.json" //do I have to explain this?
#define WHY2_VERSIONS_NAME WHY2_CONFIG_DIR "/.versions.json" //do I have to explain this?
#define WHY2_UPDATE_URL "https://github.com/ENGO150/WHY2.git" // REPOSITORY URL FOR UPDATES (YOU DON'T SAY) #define WHY2_UPDATE_URL "https://github.com/ENGO150/WHY2.git" // REPOSITORY URL FOR UPDATES (YOU DON'T SAY)
#define WHY2_UPDATE_NAME "/tmp/why2-update" // fuck you #define WHY2_UPDATE_NAME "/tmp/why2-update" // fuck you
@ -77,8 +57,6 @@ typedef struct
why2_bool no_check; //BOOLEAN FOR SKIPPING WHY2_VERSION CHECK why2_bool no_check; //BOOLEAN FOR SKIPPING WHY2_VERSION CHECK
why2_bool no_output; //BOOLEAN FOR NOT PRINTING OUTPUT WHEN ENCRYPTING/DECRYPTING why2_bool no_output; //BOOLEAN FOR NOT PRINTING OUTPUT WHEN ENCRYPTING/DECRYPTING
why2_bool update; //BOOLEAN FOR UPDATING YOUR WHY WHY2_VERSION IF OLD IS USED why2_bool update; //BOOLEAN FOR UPDATING YOUR WHY WHY2_VERSION IF OLD IS USED
enum WHY2_TEXT_KEY_CHAIN_VERSIONS version; //VERSION OF tkch
enum WHY2_OUTPUT_FORMAT format; //VERSION OF tkch
} why2_input_flags; } why2_input_flags;
typedef struct typedef struct
@ -112,8 +90,4 @@ void why2_set_encryption_operation(why2_encryption_operation_cb newEncryptionOpe
void why2_set_memory_identifier(char *new_memory_identifier); void why2_set_memory_identifier(char *new_memory_identifier);
void why2_reset_memory_identifier(void); //hmmm, what could reset mean.... huh void why2_reset_memory_identifier(void); //hmmm, what could reset mean.... huh
#ifdef __cplusplus
}
#endif
#endif #endif

View File

@ -1,52 +0,0 @@
/*
This is part of WHY2
Copyright (C) 2022 Václav Šmejkal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef WHY2_LLIST_H
#define WHY2_LLIST_H
#ifdef __cplusplus
extern "C" {
#endif
//MACROS
#define WHY2_LIST_EMPTY { NULL }
//TYPEDEFS
typedef struct _why2_node
{
void *value;
struct _why2_node *next;
} why2_node_t; //NODES
typedef struct
{
why2_node_t *head;
} why2_list_t; //SINGLE LINKED LIST MADE OF why2_node_t
//FUNCTIONS
void why2_list_push(why2_list_t *list, void *value, unsigned long size); //PUSH ELEMENT TO LIST BACK
void why2_list_remove(why2_list_t *list, why2_node_t *node); //REMOVE ELEMENT
void why2_list_remove_back(why2_list_t *list); //REMOVE LAST ELEMENT
why2_node_t *why2_list_find(why2_list_t *list, void *value); //FIND ELEMENT IN LIST
unsigned long why2_list_get_size(why2_list_t *list); //GET SIZE
#ifdef __cplusplus
}
#endif
#endif

View File

@ -19,10 +19,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef WHY2_LOGGER_FLAGS_H #ifndef WHY2_LOGGER_FLAGS_H
#define WHY2_LOGGER_FLAGS_H #define WHY2_LOGGER_FLAGS_H
#ifdef __cplusplus
extern "C" {
#endif
//CONSTS //CONSTS
enum WHY2_LOGGER_EXIT_CODES //exit codes you fucking idiot (2#) enum WHY2_LOGGER_EXIT_CODES //exit codes you fucking idiot (2#)
{ {
@ -76,8 +72,4 @@ why2_log_flags why2_get_log_flags(void);
//SETTERS //SETTERS
void why2_set_log_flags(why2_log_flags why2_log_flagsNew); void why2_set_log_flags(why2_log_flags why2_log_flagsNew);
#ifdef __cplusplus
}
#endif
#endif #endif

View File

@ -19,17 +19,9 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef WHY2_LOGGER_LOGGER_H #ifndef WHY2_LOGGER_LOGGER_H
#define WHY2_LOGGER_LOGGER_H #define WHY2_LOGGER_LOGGER_H
#ifdef __cplusplus
extern "C" {
#endif
#include <why2/logger/flags.h> #include <why2/logger/flags.h>
why2_log_file why2_init_logger(char *directoryPath); //CREATES LOGGING FILE IN directoryPath why2_log_file why2_init_logger(char *directoryPath); //CREATES LOGGING FILE IN directoryPath
void why2_write_log(int loggerFile, char *logMessage); //WRITES logMessage TO loggerFile void why2_write_log(int loggerFile, char *logMessage); //WRITES logMessage TO loggerFile
#ifdef __cplusplus
}
#endif
#endif #endif

View File

@ -19,10 +19,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef WHY2_LOGGER_UTILS_C #ifndef WHY2_LOGGER_UTILS_C
#define WHY2_LOGGER_UTILS_C #define WHY2_LOGGER_UTILS_C
#ifdef __cplusplus
extern "C" {
#endif
#include <why2/logger/flags.h> #include <why2/logger/flags.h>
void why2_deallocate_logger(why2_log_file logger); //USE THIS IF YOU WANT TO DEALLOCATE FILE POINTER RETURNED BY logger'S why2_init_logger void why2_deallocate_logger(why2_log_file logger); //USE THIS IF YOU WANT TO DEALLOCATE FILE POINTER RETURNED BY logger'S why2_init_logger
@ -31,8 +27,4 @@ why2_decrypted_output why2_decrypt_logger(why2_log_file logger); //PASS logger A
why2_log_file why2_empty_log_file(); //RETURN EMTPY why2_log_file WHAT THE FUCK DID YOU EXPECT why2_log_file why2_empty_log_file(); //RETURN EMTPY why2_log_file WHAT THE FUCK DID YOU EXPECT
why2_decrypted_output why2_empty_decrypted_output(); //NO! why2_decrypted_output why2_empty_decrypted_output(); //NO!
#ifdef __cplusplus
}
#endif
#endif #endif

View File

@ -1,30 +1,6 @@
/*
This is part of WHY2
Copyright (C) 2022 Václav Šmejkal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef WHY2_MEMORY_H #ifndef WHY2_MEMORY_H
#define WHY2_MEMORY_H #define WHY2_MEMORY_H
#ifdef __cplusplus
extern "C" {
#endif
#include <why2/flags.h>
void *why2_malloc(unsigned long size); void *why2_malloc(unsigned long size);
void *why2_calloc(unsigned long element, unsigned long size); void *why2_calloc(unsigned long element, unsigned long size);
void *why2_realloc(void *pointer, unsigned long size); void *why2_realloc(void *pointer, unsigned long size);
@ -39,10 +15,4 @@ void why2_deallocate(void *pointer);
void why2_clean_memory(char *identifier); //identifier SPECIFIES WHICH NODES TO DEALLOCATE | THIS IS BASICALLY GARBAGE COLLECTOR | PASS why2_get_default_memory_identifier() FOR DEALLOCATING EVERYTHING void why2_clean_memory(char *identifier); //identifier SPECIFIES WHICH NODES TO DEALLOCATE | THIS IS BASICALLY GARBAGE COLLECTOR | PASS why2_get_default_memory_identifier() FOR DEALLOCATING EVERYTHING
why2_bool why2_allocated(void *pointer); //CHECKS IF pointer WAS ALLOCATED USING WHY2-MEM
#ifdef __cplusplus
}
#endif
#endif #endif

View File

@ -19,18 +19,13 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef WHY2_MISC_H #ifndef WHY2_MISC_H
#define WHY2_MISC_H #define WHY2_MISC_H
#ifdef __cplusplus
extern "C" {
#endif
#include <sys/time.h> #include <sys/time.h>
#include <why2/flags.h> #include <why2/flags.h>
void why2_generate_text_key_chain(char *key, int *text_key_chain, int text_key_chain_size); //GENERATES ARRAY FOR ENCRYPTION/DECRYPTION void why2_generate_text_key_chain(char *key, int *textKeyChain, int textKeyChainSize); //GENERATES ARRAY FOR ENCRYPTION/DECRYPTION
char *why2_generate_key(int key_length); //GENERATE ENCRYPTION KEY char *why2_generate_key(int key_length); //GENERATE ENCRYPTION KEY
void why2_deallocate_output(why2_output_flags flags); //DEALLOCATES flags void why2_deallocate_output(why2_output_flags flags); //DEALLOCATES flags
void why2_directory(void); //GENERATE WHY2_CONFIG_DIR
enum WHY2_EXIT_CODES why2_check_version(void); //THIS FUNCTION CHECKS IF LATEST WHY2_VERSION OF WHY2 IS USED enum WHY2_EXIT_CODES why2_check_version(void); //THIS FUNCTION CHECKS IF LATEST WHY2_VERSION OF WHY2 IS USED
enum WHY2_EXIT_CODES why2_check_key(char *key); //CHECKS IF KEY IS VALID enum WHY2_EXIT_CODES why2_check_key(char *key); //CHECKS IF KEY IS VALID
enum WHY2_EXIT_CODES why2_check_text(char *text); //CHECKS IF TEXT IS VALID enum WHY2_EXIT_CODES why2_check_text(char *text); //CHECKS IF TEXT IS VALID
@ -38,12 +33,5 @@ unsigned long why2_count_int_length(int number); //RETURNS LENGTH OF number
unsigned long why2_count_unused_key_size(char *text, char *key); //COUNT unused_key_size unsigned long why2_count_unused_key_size(char *text, char *key); //COUNT unused_key_size
unsigned long why2_count_repeated_key_size(char *text, char *key); //COUNT repeated_key_size unsigned long why2_count_repeated_key_size(char *text, char *key); //COUNT repeated_key_size
unsigned long why2_compare_time_micro(struct timeval startTime, struct timeval finishTime); //COMPARE TIMES IN MICROSECONDS unsigned long why2_compare_time_micro(struct timeval startTime, struct timeval finishTime); //COMPARE TIMES IN MICROSECONDS
void why2_die(char *exit_message); //PRINTS exit_message ERROR AND EXITS WITH CODE 1
char *why2_replace(char *string, char *old, char *new); //REPLACES old IN string WITH new
unsigned short why2_byte_format_length(char *s); //GET LENGTH OF s OF WHY2_OUTPUT_BYTE FORMAT
#ifdef __cplusplus
}
#endif
#endif #endif

View File

@ -25,15 +25,10 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef WHY2_WHY2_H #ifndef WHY2_WHY2_H
#define WHY2_WHY2_H #define WHY2_WHY2_H
#ifdef __cplusplus
extern "C" {
#endif
//CORE //CORE
#include <why2/decrypter.h> #include <why2/decrypter.h>
#include <why2/encrypter.h> #include <why2/encrypter.h>
#include <why2/flags.h> #include <why2/flags.h>
#include <why2/llist.h>
#include <why2/memory.h> #include <why2/memory.h>
#include <why2/misc.h> #include <why2/misc.h>
@ -42,14 +37,4 @@ extern "C" {
#include <why2/logger/logger.h> #include <why2/logger/logger.h>
#include <why2/logger/utils.h> #include <why2/logger/utils.h>
//CHAT
#include <why2/chat/config.h>
#include <why2/chat/crypto.h>
#include <why2/chat/flags.h>
#include <why2/chat/misc.h>
#ifdef __cplusplus
}
#endif
#endif #endif

View File

@ -1,9 +0,0 @@
WHY2-Chat's Client & Server
===========================
*In development, do not use.*
WHY2's Chat is another encrypted and completely private communication.
All messages are encrypted with WHY2 and only you know the key (even the server can't decrypt the messages).
I am not responsible for any abuse of privacy.

View File

@ -1,148 +0,0 @@
/*
This is part of WHY2
Copyright (C) 2022 Václav Šmejkal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <why2/chat/config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <curl/curl.h>
#include <why2/flags.h>
#include <why2/memory.h>
#include <why2/misc.h>
//LOCAL
enum CONFIG_TYPES
{
CLIENT,
SERVER
};
void init_config(char *filename)
{
//CREATE USER CONFIG FOLDER [THIS SHOULDN'T HAPPEN ON CLIENT, BUT IT'S NEEDED ON FRESH SERVERS]
why2_directory();
//GET THE CONFIG TYPE
char *buffer = why2_malloc(strlen(WHY2_CONFIG_DIR) + strlen(filename) + 2);
sprintf(buffer, "%s/%s", WHY2_CONFIG_DIR, filename);
char *path = why2_replace(buffer, "{USER}", getenv("USER"));
if (access(path, R_OK) != 0) //CONFIG DOESN'T EXIST
{
char *config_dir = why2_replace(WHY2_CONFIG_DIR, "{USER}", getenv("USER"));
//CREATE CONFIG DIRECTORY
mkdir(config_dir, 0700);
CURL *curl = curl_easy_init();
FILE *file_buffer = why2_fopen(path, "w+");
buffer = why2_realloc(buffer, strlen(WHY2_CHAT_CONFIG_URL) + strlen(filename) + 1);
sprintf(buffer, "%s%s", WHY2_CHAT_CONFIG_URL, filename);
//DOWNLOAD CONTENT
curl_easy_setopt(curl, CURLOPT_URL, buffer);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, file_buffer);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, WHY2_CURL_TIMEOUT);
curl_easy_perform(curl);
//CLEANUP
curl_easy_cleanup(curl);
why2_deallocate(config_dir);
why2_deallocate(file_buffer);
}
//DEALLOCATION
why2_deallocate(path);
why2_deallocate(buffer);
}
char *config(char *key, enum CONFIG_TYPES type)
{
char *path = NULL;
switch (type) //GET path
{
case CLIENT:
path = why2_replace(WHY2_CONFIG_DIR "/" WHY2_CHAT_CONFIG_CLIENT, "{USER}", getenv("USER"));
break;
case SERVER:
path = why2_replace(WHY2_CONFIG_DIR "/" WHY2_CHAT_CONFIG_SERVER, "{USER}", getenv("USER"));
break;
default:
why2_die("CONFIG_TYPE not implemented!");
break;
}
//VALUE
char *value = why2_toml_read(path, key);
//DEALLOCATION
why2_deallocate(path);
return value;
}
//GLOBAL
void why2_chat_init_server_config(void)
{
init_config(WHY2_CHAT_CONFIG_SERVER);
//CHECK FOR USER CONFIG
char *user_pick_username = why2_chat_server_config("user_pick_username");
char *config_path = why2_replace(WHY2_CONFIG_DIR "/" WHY2_CHAT_CONFIG_SERVER_USERS, "{USER}", getenv("USER"));
if (strcmp(user_pick_username, "true") == 0 && access(config_path, R_OK) != 0)
{
//CREATE THE CONFIG
FILE *config_file = why2_fopen(config_path, "w");
//WRITE SOMETHING POSITIVE TO THE CONFIG :) (i love you, ignore my aggressive ass)
fwrite("#haha no users registered, what a loser lol", 1, 43, config_file);
//CLEANUP
why2_deallocate(config_file);
}
//DEALLOCATION
why2_toml_read_free(user_pick_username);
why2_deallocate(config_path);
}
void why2_chat_init_client_config(void)
{
init_config(WHY2_CHAT_CONFIG_CLIENT);
}
char *why2_chat_server_config(char *key)
{
return config(key, SERVER);
}
char *why2_chat_client_config(char *key)
{
return config(key, CLIENT);
}

View File

@ -1,27 +0,0 @@
# This is part of WHY2
# Copyright (C) 2022 Václav Šmejkal
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
[package]
name = "why2_chat_config"
version = "0.1.0"
edition = "2021"
[lib]
name = "why2_chat_config"
crate-type = ["cdylib"]
[dependencies]
toml = "*"

View File

@ -1,18 +0,0 @@
# This is part of WHY2
# Copyright (C) 2022 Václav Šmejkal
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
auto_connect = false # Automatic connection to 'auto_connect_ip'
auto_connect_ip = "109.123.243.163" # See 'auto_connect'

View File

@ -1,28 +0,0 @@
# This is part of WHY2
# Copyright (C) 2022 Václav Šmejkal
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
user_pick_username = true # User will be prompted for their username on connect or will end up with default_username
server_name = "WHY2 Server" # Name of the server
server_username = "server" # Username server will use
default_username = "anon" # If user_pick_username is set to false, this will be used as client username
communication_time = 300 # Seconds waiting for client message before stopping communication
max_username_length = 20 # Maximal username length
min_username_length = 4 # Minimal username length
max_username_tries = 3 # Times asking client for username (if client tries to use invalid username)
max_message_length = 100 # Maximal message length

View File

@ -1,172 +0,0 @@
/*
This is part of WHY2
Copyright (C) 2022 Václav Šmejkal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use std::
{
os::raw::c_char,
fs::
{
read_to_string,
write,
},
ffi::
{
CString,
CStr,
},
};
use toml::Value;
#[no_mangle]
pub extern "C" fn why2_toml_read(path: *const c_char, key: *const c_char) -> *mut c_char
{
//CONVERT C STRINGS TO RUST STRINGS
let path_r = unsafe { CStr::from_ptr(path).to_string_lossy().into_owned() };
let key_r = unsafe { CStr::from_ptr(key).to_string_lossy().into_owned() };
//GET FILE CONTENT
let file_raw = match read_to_string(&path_r)
{
Ok(raw) => raw,
Err(e) => panic!("Could not read TOML config: {}\n{}", path_r, e),
};
//PARSE FILE
let data: toml::Value = match toml::from_str(&file_raw)
{
Ok(data) => data,
Err(e) => panic!("Could not parse TOML config: {}\n{}", path_r, e),
};
//GET VALUE BY key_r
let mut value = match data.get(&key_r)
{
Some(value) => value.to_string(),
None => panic!("Key \"{}\" not found in TOML config: {}", key_r, path_r),
};
value = value.replace("\"", "").trim().to_string(); //REMOVE QUOTES
CString::new(value).unwrap().into_raw()
}
#[no_mangle]
pub extern "C" fn why2_toml_write(path: *const c_char, key: *const c_char, value: *const c_char)
{
//CONVERT C STRINGS TO RUST STRINGS
let path_r = unsafe { CStr::from_ptr(path).to_string_lossy().into_owned() };
let key_r = unsafe { CStr::from_ptr(key).to_string_lossy().into_owned() };
let value_r = unsafe { CStr::from_ptr(value).to_string_lossy().into_owned() };
//GET FILE CONTENT
let file_raw = match read_to_string(&path_r)
{
Ok(raw) => raw,
Err(e) =>
{
eprintln!("Could not read TOML config: {}\n{}", path_r, e);
return;
},
};
//PARSE FILE
let mut data: Value = match toml::from_str(&file_raw)
{
Ok(data) => data,
Err(e) =>
{
eprintln!("Could not parse TOML config: {}\n{}", path_r, e);
return;
},
};
//INSERT VALUE (OR UPDATE)
if let Some(table) = data.as_table_mut()
{
table.insert(key_r, Value::String(value_r));
} else
{
eprintln!("Failed to get TOML table from file: {}", path_r);
return;
}
//CONVERT NEW DATA TO STRING
let updated_data = match toml::to_string(&data)
{
Ok(data) => data,
Err(e) =>
{
eprintln!("Failed to convert TOML data to string: {}\n{}", path_r, e);
return;
},
};
//WRITE NEW DATA
if let Err(e) = write(&path_r, updated_data)
{
eprintln!("Could not write to TOML config: {}\n{}", path_r, e);
}
}
#[no_mangle]
pub extern "C" fn why2_toml_contains(path: *const c_char, key: *const c_char) -> bool
{
//CONVERT C STRINGS TO RUST STRINGS
let path_r = unsafe { CStr::from_ptr(path).to_string_lossy().into_owned() };
let key_r = unsafe { CStr::from_ptr(key).to_string_lossy().into_owned() };
//GET FILE CONTENT
let file_raw = match read_to_string(&path_r)
{
Ok(raw) => raw,
Err(e) =>
{
eprintln!("Could not read TOML config: {}\n{}", path_r, e);
return false;
},
};
//PARSE FILE
let data: Value = match toml::from_str(&file_raw)
{
Ok(data) => data,
Err(e) =>
{
eprintln!("Could not parse TOML config: {}\n{}", path_r, e);
return false;
},
};
data.get(&key_r).is_some()
}
#[no_mangle]
pub extern "C" fn why2_toml_read_free(s: *mut c_char) //BECAUSE THIS IS RUST MODULE I HAVE TO CREATE A DEALLOCATING FUNCTION
{
unsafe //DON'T TRUST THIS, I DEFINITELY KNOW WHAT I'M DOING (idk)
{
if s.is_null() //bro
{
return;
}
drop(CString::from_raw(s)); //DROP THE PTR
}
}

View File

@ -1,205 +0,0 @@
/*
This is part of WHY2
Copyright (C) 2022 Václav Šmejkal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <why2/chat/crypto.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/random.h>
#include <why2/memory.h>
#include <why2/misc.h>
#include <gmp.h>
//DO NOT TOUCH THESE PLS :3
char *rsa_modulus = NULL; //THE RSA MODULUS
char *rsa_d = NULL; //THE RSA d
//LOCAL
void generate_prime(mpz_t x)
{
//RANDOM
gmp_randstate_t state;
gmp_randinit_default(state);
unsigned long random_buffer; //SEED
do
{
if (getrandom(&random_buffer, sizeof(unsigned long), GRND_NONBLOCK) == -1) why2_die("getrandom fn failed!");
//GENERATE RANDOM PRIME USING random_buffer SEED
gmp_randseed_ui(state, random_buffer);
mpz_urandomb(x, state, WHY2_CHAT_KEY_BITS);
mpz_nextprime(x, x);
} while (mpz_probab_prime_p(x, WHY2_CHAT_PRIME_ITERS) == 0); //CHECK FOR PRIME PROBABILITY
//DEALLOCATION
gmp_randclear(state);
}
void read_file(FILE *file, char **output)
{
//VARIABLES
int buffer_size;
char *buffer;
//GET LENGTH
fseek(file, 0, SEEK_END);
buffer_size = ftell(file);
rewind(file);
//READ
buffer = why2_calloc(buffer_size + 1, sizeof(char));
if (fread(buffer, buffer_size, 1, file) != 1) why2_die("Reading keyfile failed!");
buffer[buffer_size] = '\0';
//ASSIGN OUTPUT
*output = buffer;
}
char *exp_mod(char *to_exp, char *exponent)
{
//VARIABLES
char *output;
mpz_t m, c, n, e;
mpz_init(c);
//GET ALL STUFF
mpz_init_set_str(m, to_exp, 10);
mpz_init_set_str(n, why2_get_chat_modulus(), WHY2_CHAT_KEY_BASE);
mpz_init_set_str(e, exponent, WHY2_CHAT_KEY_BASE);
//ENCRYPT MESSAGE
mpz_powm(c, m, e, n);
output = why2_malloc(mpz_sizeinbase(c, 10) + 2); //ALLOCATE OUTPUT
mpz_get_str(output, 10, c); //GET OUTPUT
//DEALLOCATION
mpz_clears(m, c, n, e, NULL);
return output;
}
//GLOBAL
void why2_chat_init_keys(void)
{
//KEY FILES
FILE *public; //TECHNICALLY, PUBLIC KEY CONTAINS ONLY THE MODULUS AND PRIVATE CONTAINS ONLY THE d
FILE *private;
//GET PATH TO KEY DIR
char *path = why2_replace(WHY2_CHAT_KEY_LOCATION, "{USER}", getenv("USER"));
//ALLOCATE THE KEY PATHS
char *public_path = why2_malloc(strlen(path) + strlen(WHY2_CHAT_PUB_KEY) + 3);
char *private_path = why2_malloc(strlen(path) + strlen(WHY2_CHAT_PRI_KEY) + 3);
//GET THE ACTUAL KEY PATHS
sprintf(public_path, "%s/%s%c", path, WHY2_CHAT_PUB_KEY, '\0');
sprintf(private_path, "%s/%s%c", path, WHY2_CHAT_PRI_KEY, '\0');
//CHECK IF KEYS EXIST
if (access(path, R_OK) != 0)
{
mkdir(path, 0700);
//SOME USER OUTPUT
printf("You are probably running WHY2-Chat for the first time now.\nGenerating RSA keys...\n");
//VARIABLES
mpz_t p, q, e, d, n, phi_n, buffer_1, buffer_2;
mpz_inits(p, q, e, d, n, phi_n, buffer_1, buffer_2, NULL);
//GENERATE PRIMES
generate_prime(p);
generate_prime(q);
//SET e
mpz_set_str(e, WHY2_CHAT_RSA_EXPONENT, 10);
//GET n
mpz_mul(n, p, q);
//GET phi
mpz_sub_ui(buffer_1, p, 1);
mpz_sub_ui(buffer_2, q, 1);
mpz_mul(phi_n, buffer_1, buffer_2);
//COUNT d
mpz_invert(d, e, phi_n);
printf("Saving keys...\n");
//WRITE THE KEYS INTO KEY-FILES
public = why2_fopen(public_path, "w+");
private = why2_fopen(private_path, "w+");
mpz_out_str(public, WHY2_CHAT_KEY_BASE, n);
mpz_out_str(private, WHY2_CHAT_KEY_BASE, d);
//KEYGEN DEALLOCATION
mpz_clears(p, q, e, d, n, phi_n, buffer_1, buffer_2, NULL);
} else
{
//OPEN FILES
public = why2_fopen(public_path, "r");
private = why2_fopen(private_path, "r");
//READ THE KEYS
read_file(public, &rsa_modulus);
read_file(private, &rsa_d);
}
//DEALLOCATION
why2_deallocate(path);
why2_deallocate(public_path);
why2_deallocate(private_path);
why2_deallocate(public);
why2_deallocate(private);
}
void why2_chat_deallocate_keys(void)
{
why2_deallocate(rsa_modulus);
why2_deallocate(rsa_d);
}
char *why2_get_chat_modulus(void)
{
return rsa_modulus;
}
char *why2_get_chat_d(void)
{
return rsa_d;
}
char *why2_chat_rsa_pub_encrypt(char *to_encrypt)
{
return exp_mod(to_encrypt, WHY2_CHAT_RSA_EXPONENT);
}
char *why2_chat_rsa_pri_decrypt(char *to_decrypt)
{
return exp_mod(to_decrypt, why2_get_chat_d());
}

View File

@ -1,281 +0,0 @@
/*
This is part of WHY2
Copyright (C) 2022 Václav Šmejkal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <why2/chat/config.h>
#include <why2/chat/crypto.h>
#include <why2/chat/flags.h>
#include <why2/chat/misc.h>
#include <why2/flags.h>
#include <why2/memory.h>
#include <why2/misc.h>
why2_bool exited = 0; //USER ALREADY REQUESTED EXIT
int listen_socket; //THE SERVER SOCKET
void exit_client(WHY2_UNUSED int i) //guess what
{
if (exited) return;
exited = 1;
why2_send_socket(WHY2_CHAT_CODE_EXIT, NULL, listen_socket);
}
why2_bool command(char *input, char *command, char **arg)
{
why2_bool returning = 0;
//GET THE COMMANDS
char *full_cmd = why2_malloc(strlen(WHY2_CHAT_COMMAND_PREFIX) + strlen(WHY2_CHAT_COMMAND_EXIT) + 2);
sprintf(full_cmd, WHY2_CHAT_COMMAND_PREFIX "%s", command);
//CLEAR arg
why2_deallocate(*arg); //DEALLOCATION (why2_deallocate fn checks for NULL, don't you worry)
*arg = NULL;
if (strncmp(input, full_cmd, strlen(full_cmd)) == 0) //COMMAND WAS EXECUTED
{
if (strlen(full_cmd) == strlen(input) - 1) //COMMAND DOESN'T HAVE ARGS
{
returning = 1;
} else if (strlen(input) - 2 > strlen(full_cmd) && input[strlen(full_cmd)] == ' ') //COMMAND CONTAINS ARGS
{
returning = 1;
//GET THE ARGS
*arg = why2_malloc(strlen(input) - strlen(full_cmd) - 1); //ALLOCATE
for (unsigned long i = strlen(full_cmd) + 1; i < strlen(input) - 1; i++)
{
(*arg)[i - (strlen(full_cmd) + 1)] = input[i];
}
(*arg)[strlen(input) - strlen(full_cmd) - 2] = '\0'; //NULL TERM
why2_trim_string(arg);
}
}
//DEALLOCATE BUFFERS
why2_deallocate(full_cmd);
return returning;
}
void invalid(char *type)
{
printf("\nInvalid %s! Use \"" WHY2_CHAT_COMMAND_PREFIX WHY2_CHAT_COMMAND_HELP "\" for list of commands.\n\n>>> ", type);
fflush(stdout);
}
int main(void)
{
signal(SIGINT, exit_client); //HANDLE ^C
why2_check_version(); //CHECK FOR UPDATES
why2_chat_init_client_config(); //CREATE client.toml CONFIGURATION
why2_chat_init_keys(); //CREATE RSA KEYS
listen_socket = socket(AF_INET, SOCK_STREAM, 0); //CREATE SERVER SOCKET
char *line = NULL;
void *return_line = NULL;
size_t line_length = 0;
pthread_t thread_buffer;
pthread_t thread_getline;
why2_bool ssqc = 0;
char *cmd_arg = NULL;
//DEFINE SERVER ADDRESS
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(WHY2_CHAT_SERVER_PORT);
//GET IP
printf("Welcome.\n\n");
char *auto_connect = why2_chat_client_config("auto_connect");
if (strcmp(auto_connect, "true") == 0) //USER ENABLED AUTOMATIC CONNECTION
{
char *auto_connect_ip = why2_chat_client_config("auto_connect_ip"); //GET IP
line = strdup(auto_connect_ip);
printf("%s\n", line);
why2_toml_read_free(auto_connect_ip);
} else
{
printf("Enter IP Address:\n>>> ");
if (getline(&line, &line_length, stdin) == -1) why2_die("Reading input failed.");
line_length = 3; //THIS IS FOR THE UNDERLINE THINGY
}
why2_toml_read_free(auto_connect);
server_addr.sin_addr.s_addr = inet_addr(line);
//PRINT UNDERLINE
for (unsigned long i = 0; i < strlen(line) + line_length; i++)
{
printf("#");
}
printf("\n\n\n");
free(line); //PREVENT FROM MEMORY LEAK
int connectStatus = connect(listen_socket, (WHY2_SA *) &server_addr, sizeof(server_addr)); //CONNECT
if (connectStatus < 0) why2_die("Connecting failed.");
pthread_create(&thread_buffer, NULL, why2_listen_server, &listen_socket); //LISTEN TO OTHER USERS
for (;;)
{
pthread_create(&thread_getline, NULL, why2_getline_thread, NULL);
pthread_join(thread_getline, &return_line);
if (return_line == WHY2_INVALID_POINTER) //SERVER QUIT COMMUNICATION
{
ssqc = 1;
break;
}
line = (char*) return_line;
why2_trim_string(&line);
if (line == NULL) line = strdup("");
printf(WHY2_CLEAR_AND_GO_UP);
//TODO: Remove accents
if (strncmp(line, WHY2_CHAT_COMMAND_PREFIX, strlen(WHY2_CHAT_COMMAND_PREFIX)) == 0) //OPTIMIZE COMMANDS
{
//COMMANDS
if (command(line, WHY2_CHAT_COMMAND_EXIT, &cmd_arg)) //USER REQUESTED PROGRAM EXIT
{
printf("Exiting...\n");
exit_client(0);
} else if (command(line, WHY2_CHAT_COMMAND_HELP, &cmd_arg)) //HELP CMD
{
printf
(
"\nCommands:\n---------\n%s\n\n>>> ",
WHY2_CHAT_COMMAND_PREFIX WHY2_CHAT_COMMAND_HELP "\t\tPrints out all the commands. :)\n"
WHY2_CHAT_COMMAND_PREFIX WHY2_CHAT_COMMAND_PM " <ID> <MSG>\tSends private message to user.\n"
WHY2_CHAT_COMMAND_PREFIX WHY2_CHAT_COMMAND_LIST "\t\tLists all users and their IDs.\n"
WHY2_CHAT_COMMAND_PREFIX WHY2_CHAT_COMMAND_VERSION "\tCheck server version.\n"
WHY2_CHAT_COMMAND_PREFIX WHY2_CHAT_COMMAND_EXIT "\t\tExits the program."
);
fflush(stdout);
} else if (command(line, WHY2_CHAT_COMMAND_PM, &cmd_arg))
{
char *id; //PM RECEIVER
WHY2_UNUSED char *msg; //something racial
//CHECK ARGS VALIDITY
why2_bool valid_param = cmd_arg != NULL && strlen(cmd_arg) >= 3;
if (valid_param)
{
valid_param = 0;
for (unsigned long i = 1; i < strlen(cmd_arg); i++)
{
if (cmd_arg[i] == ' ')
{
valid_param = 1;
//EXTRACT FIRST ARG (ID)
id = why2_malloc(i + 1);
for (unsigned long j = 0; j < i; j++)
{
id[j] = cmd_arg[j];
}
id[i] = '\0';
if (atoi(id) <= 0) //INVALID ID PASSED
{
valid_param = 0;
why2_deallocate(id);
break;
}
//EXTRACT MESSAGE
msg = cmd_arg + i + 1;
break;
}
}
}
if (!valid_param) //INVALID ARGS
{
invalid("usage");
continue;
}
//BUILD MESSAGE TO SEND TO SERVER
char *final_message = why2_malloc(strlen(WHY2_CHAT_CODE_PM) + strlen(id) + strlen(msg) + 3);
sprintf(final_message, WHY2_CHAT_CODE_PM ";%s;%s%c", id, msg, '\0');
why2_send_socket(final_message, NULL, listen_socket); //SEND
//DEALLOCATION
why2_deallocate(id);
why2_deallocate(final_message);
} else if (command(line, WHY2_CHAT_COMMAND_LIST, &cmd_arg)) //LIST CMD
{
why2_send_socket(WHY2_CHAT_CODE_LIST, NULL, listen_socket);
} else if (command(line, WHY2_CHAT_COMMAND_VERSION, &cmd_arg)) //VERSION CMD
{
why2_send_socket(WHY2_CHAT_CODE_VERSION, NULL, listen_socket);
} else
{
invalid("command");
}
} else
{
why2_send_socket(line, NULL, listen_socket); //NULL IS SENT BECAUSE IT IS USELESS TO SEND USER FROM CLIENT - SERVER WON'T USE IT
free(line);
}
}
//DEALLOCATION
if (!ssqc)
{
pthread_cancel(thread_buffer);
free(line);
}
why2_deallocate(cmd_arg);
why2_chat_deallocate_keys(); //DEALLOCATE GETTERS FOR KEYS
why2_clean_memory(""); //RUN GARBAGE COLLECTOR
return 0;
}

View File

@ -1,86 +0,0 @@
/*
This is part of WHY2
Copyright (C) 2022 Václav Šmejkal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <pthread.h>
#include <why2/chat/config.h>
#include <why2/chat/flags.h>
#include <why2/chat/misc.h>
#include <why2/memory.h>
#include <why2/misc.h>
int main(void)
{
why2_check_version(); //CHECK FOR UPDATES
why2_chat_init_server_config(); //CREATE server.toml CONFIGURATION
int listen_socket = socket(AF_INET, SOCK_STREAM, 0); //CREATE SERVER SOCKET
pthread_t thread;
size_t line_length_buffer = 0;
char *line_buffer = NULL;
if (listen_socket < 0) why2_die("Failed creating socket.");
//DEFINE SERVER ADDRESS
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(WHY2_CHAT_SERVER_PORT);
server_addr.sin_addr.s_addr = INADDR_ANY;
//BIND SOCKET
if (bind(listen_socket, (WHY2_SA *) &server_addr, sizeof(server_addr)) < 0) why2_die("Failed binding socket.");
//LISTEN
if (listen(listen_socket, WHY2_MAX_CONNECTIONS) < 0) why2_die("Binding failed.");
printf("Server enabled.\n\n");
pthread_create(&thread, NULL, why2_accept_thread, &listen_socket);
for (;;)
{
if (getline(&line_buffer, &line_length_buffer, stdin) == -1) why2_die("Reading input failed.");
if (strcmp(line_buffer, WHY2_CHAT_COMMAND_PREFIX WHY2_CHAT_COMMAND_EXIT "\n") == 0) //USER REQUESTED PROGRAM EXIT
{
printf("Exiting...\n");
break;
}
}
//QUIT COMMUNICATION
why2_clean_connections(); //STOP LISTENING; DISCONNECT ALL USERS
why2_clean_threads(); //STOP WAITING FOR MESSAGES
//DEALLOCATION
free(line_buffer);
close(listen_socket);
pthread_cancel(thread);
why2_clean_memory(""); //RUN GARBAGE COLLECTOR
return 0;
}

File diff suppressed because it is too large Load Diff

View File

@ -23,7 +23,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
int main(void) int main(void)
{ {
//SET FLAGS //SET FLAGS
why2_set_flags((why2_input_flags) { 1, 1, 0, WHY2_v3, WHY2_OUTPUT_TEXT }); why2_set_flags((why2_input_flags) {1, 1, 0});
//RUN ENCRYPTION WITH WHY2_TEXT_TO_ENCRYPT, GENERATE NEW KEY AND DO NOT CHECK FOR ACTIVE WHY2_VERSION & PREVENT ANY OUTPUT //RUN ENCRYPTION WITH WHY2_TEXT_TO_ENCRYPT, GENERATE NEW KEY AND DO NOT CHECK FOR ACTIVE WHY2_VERSION & PREVENT ANY OUTPUT
why2_output_flags encryptedText = why2_encrypt_text(WHY2_TEXT_TO_ENCRYPT, NULL); why2_output_flags encryptedText = why2_encrypt_text(WHY2_TEXT_TO_ENCRYPT, NULL);

View File

@ -27,179 +27,129 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <why2/memory.h> #include <why2/memory.h>
#include <why2/misc.h> #include <why2/misc.h>
why2_output_flags why2_decrypt_text(char *text, char *key_new) why2_output_flags why2_decrypt_text(char *text, char *keyNew)
{ {
//CHECK VARIABLE //CHECK VARIABLE
unsigned char check_exit_code; unsigned char checkExitCode;
//TIME VARIABLES //TIME VARIABLES
struct timeval start_time; struct timeval startTime;
struct timeval finish_time; struct timeval finishTime;
gettimeofday(&start_time, NULL); gettimeofday(&startTime, NULL);
//CHECK FOR ACTIVE WHY2_VERSION //CHECK FOR ACTIVE WHY2_VERSION
if ((check_exit_code = why2_check_version()) != WHY2_SUCCESS) if ((checkExitCode = why2_check_version()) != WHY2_SUCCESS)
{ {
return why2_no_output(check_exit_code); return why2_no_output(checkExitCode);
} }
//CHECK FOR INVALID text //CHECK FOR INVALID text
if ((check_exit_code = why2_check_text(text)) != WHY2_SUCCESS) if ((checkExitCode = why2_check_text(text)) != WHY2_SUCCESS)
{ {
return why2_no_output(check_exit_code); return why2_no_output(checkExitCode);
} }
//CHECK FOR INVALID key //CHECK FOR INVALID key
if ((check_exit_code = why2_check_key(key_new)) != WHY2_SUCCESS) if ((checkExitCode = why2_check_key(keyNew)) != WHY2_SUCCESS)
{ {
return why2_no_output(check_exit_code); return why2_no_output(checkExitCode);
} }
//REDEFINE keyLength //REDEFINE keyLength
why2_set_key_length(strlen(key_new)); why2_set_key_length(strlen(keyNew));
//VARIABLES //VARIABLES
char *returning_text; char *returningText;
int number_buffer = 0; int numberBuffer = 1;
int used_text_deallocation_buffer = 0; int usedTextDeallocationBuffer = 0;
char *text_buffer = NULL; char *textBuffer = NULL;
int text_key_chainLength; int textKeyChainLength;
int *text_key_chain; int *textKeyChain;
char *key = why2_strdup(key_new); //COPY key_new TO key char *key = why2_strdup(keyNew); //COPY keyNew TO key
int *encrypted_text_key_chain; int *encryptedTextKeyChain;
char *used_text = NULL; //COPY text TO used_text char *used_text = why2_strdup(text); //COPY text TO used_text
if (why2_get_flags().format == WHY2_OUTPUT_BYTE) //GET LENGTH OF returningText AND textKeyChain
{
//REBUILD THE BYTE FORMAT AS TEXT FORMAT
int *encrypted_input = why2_malloc(sizeof(int) * why2_byte_format_length(text));
char *text_copy = why2_strdup(text);
//GET ENCRYPTED NUMBERS
for (unsigned short i = 0; i < why2_byte_format_length(text_copy); i++)
{
for (unsigned short j = 2 + (i * 2); j <= 3 + (i * 2); j++)
{
//ENSURE THERE IS NO \0 (REVERSED)
if (text_copy[j] == -128) text_copy[j] = 0;
}
//PUT TOGETHER
encrypted_input[i] = (text_copy[3 + (i * 2)] << 7) | text_copy[2 + (i * 2)];
//ALSO COUNT REQUIRED SIZE
number_buffer += why2_count_int_length(encrypted_input[i]);
}
number_buffer += why2_byte_format_length(text_copy); //ADD THE SEPARATORS (I didn't remove one cause 1 index will be empty at used_text end)
used_text = why2_calloc(number_buffer, sizeof(char));
for (unsigned short i = 0; i < why2_byte_format_length(text_copy); i++)
{
number_buffer = why2_count_int_length(encrypted_input[i]);
text_buffer = why2_realloc(text_buffer, number_buffer + 1);
sprintf(text_buffer, "%d", encrypted_input[i]);
strcat(used_text, text_buffer);
if (i != why2_byte_format_length(text_copy) - 1)
{
used_text[strlen(used_text)] = why2_get_encryption_separator();
}
}
//DEALLOCATION
why2_deallocate(encrypted_input);
why2_deallocate(text_buffer);
why2_deallocate(text_copy);
} else if (why2_get_flags().format == WHY2_OUTPUT_TEXT)
{
used_text = why2_strdup(text);
}
number_buffer = 1;
//GET LENGTH OF returning_text AND text_key_chain
for (int i = 0; i < (int) strlen(used_text); i++) for (int i = 0; i < (int) strlen(used_text); i++)
{ {
if (used_text[i] == why2_get_encryption_separator()) number_buffer++; if (used_text[i] == why2_get_encryption_separator()) numberBuffer++;
} }
//SET LENGTH (number_buffer) //SET LENGTH (numberBuffer)
returning_text = why2_calloc(number_buffer + 1, sizeof(char)); returningText = why2_calloc(numberBuffer + 1, sizeof(char));
text_key_chain = why2_malloc(sizeof(int) * number_buffer); textKeyChain = why2_malloc(sizeof(int) * numberBuffer);
encrypted_text_key_chain = why2_malloc(sizeof(int) * number_buffer); encryptedTextKeyChain = why2_malloc(sizeof(int) * numberBuffer);
text_key_chainLength = number_buffer; textKeyChainLength = numberBuffer;
//LOAD text_key_chain //LOAD textKeyChain
why2_generate_text_key_chain(key, text_key_chain, number_buffer); why2_generate_text_key_chain(key, textKeyChain, numberBuffer);
//LOAD encrypted_text_key_chain //LOAD encryptedTextKeyChain
for (int i = 0; i < text_key_chainLength; i++) for (int i = 0; i < textKeyChainLength; i++)
{ {
number_buffer = 0; numberBuffer = 0;
//GET LENGTH OF EACH CHARACTER //GET LENGTH OF EACH CHARACTER
for (int j = 0; j < (int) strlen(used_text); j++) for (int j = 0; j < (int) strlen(used_text); j++)
{ {
if (used_text[j] == why2_get_encryption_separator()) break; if (used_text[j] == why2_get_encryption_separator()) break;
number_buffer++; numberBuffer++;
} }
text_buffer = why2_realloc(text_buffer, number_buffer + 1); textBuffer = why2_realloc(textBuffer, numberBuffer + 1);
//CLEAN (POSSIBLY EXISTING) JUNK in text_buffer //CLEAN (POSSIBLY EXISTING) JUNK in textBuffer
for (int j = 0; j <= number_buffer; j++) for (int j = 0; j <= numberBuffer; j++)
{ {
text_buffer[j] = '\0'; textBuffer[j] = '\0';
} }
//LOAD text_buffer //LOAD textBuffer
for (int j = 0; j < (int) strlen(used_text); j++) for (int j = 0; j < (int) strlen(used_text); j++)
{ {
text_buffer[j] = used_text[j]; textBuffer[j] = used_text[j];
if (number_buffer == j) break; if (numberBuffer == j) break;
} }
encrypted_text_key_chain[i] = atoi(text_buffer); encryptedTextKeyChain[i] = atoi(textBuffer);
used_text += number_buffer + 1; used_text += numberBuffer + 1;
used_text_deallocation_buffer += number_buffer + 1; usedTextDeallocationBuffer += numberBuffer + 1;
} }
//DECRYPT TEXT //DECRYPT TEXT
for (int i = 0; i < text_key_chainLength; i++) for (int i = 0; i < textKeyChainLength; i++)
{ {
text_key_chain[i] = why2_get_encryption_operation()(text_key_chain[i], encrypted_text_key_chain[i]); textKeyChain[i] = why2_get_encryption_operation()(textKeyChain[i], encryptedTextKeyChain[i]);
} }
//LOAD returning_text //LOAD returningText
for (int i = 0; i < text_key_chainLength; i++) for (int i = 0; i < textKeyChainLength; i++)
{ {
returning_text[i] = text_key_chain[i]; returningText[i] = textKeyChain[i];
} }
//GET FINISH TIME //GET FINISH TIME
gettimeofday(&finish_time, NULL); gettimeofday(&finishTime, NULL);
//LOAD output //LOAD output
why2_output_flags output = why2_output_flags output =
{ {
returning_text, //DECRYPTED TEXT returningText, //DECRYPTED TEXT
key, //USED KEY key, //USED KEY
why2_count_unused_key_size(returning_text, key), // NUMBER OF WHY2_UNUSED CHARS IN KEY why2_count_unused_key_size(returningText, key), // NUMBER OF WHY2_UNUSED CHARS IN KEY
why2_count_repeated_key_size(returning_text, key), //NUMBER OF REPEATED CHARS IN KEY why2_count_repeated_key_size(returningText, key), //NUMBER OF REPEATED CHARS IN KEY
why2_compare_time_micro(start_time, finish_time), // ELAPSED TIME why2_compare_time_micro(startTime, finishTime), // ELAPSED TIME
WHY2_SUCCESS //EXIT CODE WHY2_SUCCESS //EXIT CODE
}; };
//DEALLOCATION //DEALLOCATION
why2_deallocate(text_key_chain); why2_deallocate(textKeyChain);
why2_deallocate(encrypted_text_key_chain); why2_deallocate(encryptedTextKeyChain);
why2_deallocate(text_buffer); why2_deallocate(textBuffer);
why2_deallocate(used_text - used_text_deallocation_buffer); why2_deallocate(used_text - usedTextDeallocationBuffer);
return output; return output;
} }

View File

@ -26,47 +26,47 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <why2/memory.h> #include <why2/memory.h>
#include <why2/misc.h> #include <why2/misc.h>
why2_output_flags why2_encrypt_text(char *text, char *key_new) why2_output_flags why2_encrypt_text(char *text, char *keyNew)
{ {
//CHECK VARIABLE //CHECK VARIABLE
unsigned char check_exit_code; unsigned char checkExitCode;
//TIME VARIABLES //TIME VARIABLES
struct timeval start_time; struct timeval startTime;
struct timeval finish_time; struct timeval finishTime;
gettimeofday(&start_time, NULL); gettimeofday(&startTime, NULL);
//CHECK FOR ACTIVE WHY2_VERSION //CHECK FOR ACTIVE WHY2_VERSION
if ((check_exit_code = why2_check_version()) != WHY2_SUCCESS) if ((checkExitCode = why2_check_version()) != WHY2_SUCCESS)
{ {
return why2_no_output(check_exit_code); return why2_no_output(checkExitCode);
} }
//CHECK FOR INVALID text //CHECK FOR INVALID text
if ((check_exit_code = why2_check_text(text)) != WHY2_SUCCESS) if ((checkExitCode = why2_check_text(text)) != WHY2_SUCCESS)
{ {
return why2_no_output(check_exit_code); return why2_no_output(checkExitCode);
} }
why2_set_memory_identifier("core_decrypt"); why2_set_memory_identifier("core_decrypt");
//VARIABLES //VARIABLES
char *key = NULL; char *key = NULL;
char *returning_text = NULL; char *returningText;
char *text_buffer = NULL; char *textBuffer = NULL;
int *text_key_chain = why2_malloc(sizeof(int) * strlen(text)); int *textKeyChain = why2_malloc(sizeof(int) * strlen(text));
int number_buffer = 0; int numberBuffer = 0;
if (key_new != NULL) if (keyNew != NULL)
{ {
//CHECK FOR INVALID key //CHECK FOR INVALID key
if ((check_exit_code = why2_check_key(key_new)) != WHY2_SUCCESS) if ((checkExitCode = why2_check_key(keyNew)) != WHY2_SUCCESS)
{ {
why2_clean_memory("core_decrypt"); why2_clean_memory("core_decrypt");
return why2_no_output(check_exit_code); return why2_no_output(checkExitCode);
} }
key = why2_strdup(key_new); key = why2_strdup(keyNew);
//REDEFINE keyLength //REDEFINE keyLength
why2_set_key_length(strlen(key)); why2_set_key_length(strlen(key));
@ -75,85 +75,61 @@ why2_output_flags why2_encrypt_text(char *text, char *key_new)
key = why2_generate_key(why2_get_key_length()); key = why2_generate_key(why2_get_key_length());
} }
//LOAD text_key_chain //LOAD textKeyChain
why2_generate_text_key_chain(key, text_key_chain, strlen(text)); why2_generate_text_key_chain(key, textKeyChain, strlen(text));
//ACTUALLY ENCRYPT TEXT //ACTUALLY ENCRYPT TEXT
for (int i = 0; i < (int) strlen(text); i++) for (int i = 0; i < (int) strlen(text); i++)
{ {
text_key_chain[i] = why2_get_encryption_operation()(text_key_chain[i], (int) text[i]); textKeyChain[i] = why2_get_encryption_operation()(textKeyChain[i], (int) text[i]);
} }
//OUTPUT FORMATS //COUNT REQUIRED SIZE FOR returningText
if (why2_get_flags().format == WHY2_OUTPUT_TEXT) //NORMAL 420.-69 FORMAT for (int i = 0; i < (int) strlen(text); i++)
{ {
//COUNT REQUIRED SIZE FOR returning_text numberBuffer += why2_count_int_length(textKeyChain[i]);
for (int i = 0; i < (int) strlen(text); i++) }
{
number_buffer += why2_count_int_length(text_key_chain[i]);
}
//ALLOCATE returning_text (WITH THE SEPARATORS) //ALLOCATE returningText (WITH THE SEPARATORS)
returning_text = why2_calloc(number_buffer + strlen(text), sizeof(char)); returningText = why2_calloc(numberBuffer + strlen(text), sizeof(char));
//LOAD returning_text //LOAD returningText
for (int i = 0; i < (int) strlen(text); i++) for (int i = 0; i < (int) strlen(text); i++)
{
number_buffer = sizeof(int) * why2_count_int_length(text_key_chain[i]);
text_buffer = why2_realloc(text_buffer, number_buffer);
sprintf(text_buffer, "%d", text_key_chain[i]);
strcat(returning_text, text_buffer);
if (i != (int) strlen(text) - 1)
{
returning_text[strlen(returning_text)] = why2_get_encryption_separator();
}
}
} else if (why2_get_flags().format == WHY2_OUTPUT_BYTE) //FUCKED BUT SHORT(ER) OUTPUT
{ {
number_buffer = (strlen(text) + 1) * 2; //EACH CHARACTER WILL BE SPLIT INTO TWO CHARS AND FIRST TWO WILL BE LENGTH OF text numberBuffer = sizeof(int) * why2_count_int_length(textKeyChain[i]);
returning_text = why2_calloc(number_buffer + 1, sizeof(char)); //ALLOCATE textBuffer = why2_realloc(textBuffer, numberBuffer);
//SET LENGTH sprintf(textBuffer, "%d", textKeyChain[i]);
returning_text[0] = (strlen(text) & 0x7f) + 1; //+1 BECAUSE WE DON'T WANT \0
returning_text[1] = (strlen(text) >> 7) + 1;
//PUT THE text_key_chain INTO returning_text DIRECTLY strcat(returningText, textBuffer);
for (unsigned long i = 0; i < strlen(text); i++)
if (i != (int) strlen(text) - 1)
{ {
//BUILD returning_text textBuffer = why2_realloc(textBuffer, 2);
returning_text[2 + (i * 2)] = text_key_chain[i] & 0x7f; sprintf(textBuffer, "%c", why2_get_encryption_separator());
returning_text[3 + (i * 2)] = (text_key_chain[i] >> 7) | ((text_key_chain[i] < 0) ? 0x80 : 0);
for (unsigned long j = 2 + (i * 2); j <= 3 + (i * 2); j++) strcat(returningText, textBuffer);
{
//ENSURE THERE IS NO \0
if (returning_text[j] == 0) returning_text[j] = -128;
}
} }
} }
//GET FINISH TIME //GET FINISH TIME
gettimeofday(&finish_time, NULL); gettimeofday(&finishTime, NULL);
//LOAD output //LOAD output
why2_output_flags output = why2_output_flags output =
{ {
returning_text, //ENCRYPTED TEXT returningText, //ENCRYPTED TEXT
key, //GENERATED/USED KEY key, //GENERATED/USED KEY
why2_count_unused_key_size(text, key), // NUMBER OF WHY2_UNUSED CHARS IN KEY why2_count_unused_key_size(text, key), // NUMBER OF WHY2_UNUSED CHARS IN KEY
why2_count_repeated_key_size(text, key), //NUMBER OF REPEATED CHARS IN KEY why2_count_repeated_key_size(text, key), //NUMBER OF REPEATED CHARS IN KEY
why2_compare_time_micro(start_time, finish_time), // ELAPSED TIME why2_compare_time_micro(startTime, finishTime), // ELAPSED TIME
WHY2_SUCCESS //EXIT CODE WHY2_SUCCESS //EXIT CODE
}; };
//DEALLOCATION //DEALLOCATION
why2_deallocate(text_key_chain); why2_deallocate(textKeyChain);
why2_deallocate(text_buffer); why2_deallocate(textBuffer);
why2_reset_memory_identifier(); why2_reset_memory_identifier();

View File

@ -19,13 +19,11 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <why2/flags.h> #include <why2/flags.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h>
#include <why2/llist.h>
#include <why2/memory.h> #include <why2/memory.h>
//CONSTS (this is just local) //CONSTS (this is just local)
#define DEFAULT_FLAGS (why2_input_flags) { 0, 0, 0, WHY2_v3, WHY2_OUTPUT_TEXT } #define DEFAULT_FLAGS (why2_input_flags) { 0, 0, 0 }
#define DEFAULT_MEMORY_IDENTIFIER "" #define DEFAULT_MEMORY_IDENTIFIER ""
int encryptionOperation(int text, int encryptedText); int encryptionOperation(int text, int encryptedText);
@ -38,16 +36,66 @@ why2_encryption_operation_cb encryptionOperation_cb = encryptionOperation;
why2_bool flagsChanged = 0; //CHANGES TO 1 WHEN U USE why2_set_flags why2_bool flagsChanged = 0; //CHANGES TO 1 WHEN U USE why2_set_flags
char *memory_identifier = DEFAULT_MEMORY_IDENTIFIER; char *memory_identifier = DEFAULT_MEMORY_IDENTIFIER;
why2_list_t identifier_list = WHY2_LIST_EMPTY; //LINKED LIST SHIT
typedef struct node
{
char *identifier;
struct node *next;
} node_t;
node_t *list_head = NULL;
void push_to_list_end(char *identifier)
{
node_t *new_node = malloc(sizeof(node_t));
node_t *buffer = list_head;
new_node -> identifier = identifier;
new_node -> next = NULL;
if (list_head == NULL) //LIST IS EMTPY
{
list_head = new_node;
} else
{
while (buffer -> next != NULL) buffer = buffer -> next; //GO TO THE END OF LIST
buffer -> next = new_node; //LINK
}
}
void remove_node_from_end(void)
{
if (list_head == NULL) return; //EMPTY LIST
node_t *buffer = list_head;
node_t *deallocating_node;
if (buffer -> next == NULL) //ONLY ONE NODE
{
deallocating_node = buffer;
list_head = NULL;
} else
{
while (buffer -> next -> next != NULL) buffer = buffer -> next; //GO TO THE NODE BEFORE END
deallocating_node = buffer -> next;
buffer -> next = NULL; //UNLINK
}
free(deallocating_node);
}
char *get_last_node_identifier(void) char *get_last_node_identifier(void)
{ {
if (identifier_list.head == NULL) return DEFAULT_MEMORY_IDENTIFIER; if (list_head == NULL) return DEFAULT_MEMORY_IDENTIFIER;
why2_node_t *buffer = identifier_list.head; node_t *buffer = list_head;
while (buffer -> next != NULL) buffer = buffer -> next; while (buffer -> next != NULL) buffer = buffer -> next;
return buffer -> value; return buffer -> identifier;
} }
//GETTERS //GETTERS
@ -140,14 +188,14 @@ void why2_set_encryption_operation(why2_encryption_operation_cb newEncryptionOpe
void why2_set_memory_identifier(char *new_memory_identifier) void why2_set_memory_identifier(char *new_memory_identifier)
{ {
why2_list_push(&identifier_list, new_memory_identifier, strlen(new_memory_identifier) + 1); //TODO: Check memory problems push_to_list_end(new_memory_identifier);
memory_identifier = new_memory_identifier; memory_identifier = new_memory_identifier;
} }
void why2_reset_memory_identifier(void) void why2_reset_memory_identifier(void)
{ {
why2_list_remove_back(&identifier_list); remove_node_from_end();
memory_identifier = get_last_node_identifier(); memory_identifier = get_last_node_identifier();
} }

View File

@ -43,9 +43,7 @@ int main(void)
{ {
0, //SKIP CHECK 0, //SKIP CHECK
0, //NO OUTPUT 0, //NO OUTPUT
0, //UPDATE 0 //UPDATE
WHY2_v3, //LATEST VERSION
WHY2_OUTPUT_TEXT //READABLE TEXT OUTPUT
}; };
//SET FLAGS //SET FLAGS

View File

@ -1,154 +0,0 @@
/*
This is part of WHY2
Copyright (C) 2022 Václav Šmejkal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <why2/llist.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void why2_list_push(why2_list_t *list, void *value, unsigned long size)
{
//CREATE NODE
why2_node_t *head = list -> head;
why2_node_t *new_node = malloc(sizeof(why2_node_t));
new_node -> value = malloc(size);
why2_node_t *buffer = head;
//INSERT DATA
memcpy(new_node -> value, value, size);
new_node -> next = NULL;
if (head == NULL) //INIT LIST
{
buffer = new_node;
} else
{
why2_node_t *buffer_2 = buffer;
while (buffer -> next != NULL) buffer = buffer -> next; //GET TO THE END OF LIST
buffer -> next = new_node; //LINK
buffer = buffer_2; //GO BACK TO THE START OF THE LLIST
}
//APPEND THE new_node TO THE END OF list
list -> head = buffer;
}
void why2_list_remove(why2_list_t *list, why2_node_t *node)
{
if (node == NULL) return; //NULL NODE
why2_node_t *head = list -> head;
why2_node_t *buffer_1 = head;
why2_node_t *buffer_2;
while (buffer_1 -> next != NULL) //GO TROUGH EVERY ELEMENT IN LIST
{
if (buffer_1 == node) break; //FOUND (IF THE WHILE GOES TROUGH THE WHOLE LIST WITHOUT THE break, I ASSUME THE LAST NODE IS THE CORRECT ONE)
buffer_1 = buffer_1 -> next;
}
if (node != buffer_1) return; //node WASN'T FOUND
if (buffer_1 == head) //node WAS THE FIRST NODE IN THE LIST
{
//UNLINK
head = buffer_1 -> next;
} else //wdyt
{
//GET THE NODE BEFORE node
buffer_2 = head;
while (buffer_2 -> next != buffer_1) buffer_2 = buffer_2 -> next;
//UNLINK
buffer_2 -> next = buffer_1 -> next;
}
list -> head = head;
//DEALLOCATION
free(node -> value);
free(node);
}
void why2_list_remove_back(why2_list_t *list)
{
why2_node_t *head = list -> head;
if (head == NULL) return; //EMPTY LIST
why2_node_t *buffer = head;
why2_node_t *deallocating_node;
if (buffer -> next == NULL) //ONLY ONE NODE
{
deallocating_node = buffer;
list -> head = NULL;
} else
{
while (buffer -> next -> next != NULL) buffer = buffer -> next; //GO TO THE NODE BEFORE END
deallocating_node = buffer -> next;
buffer -> next = NULL; //UNLINK
}
free(deallocating_node -> value);
free(deallocating_node);
}
why2_node_t *why2_list_find(why2_list_t *list, void *value)
{
why2_node_t *head = list -> head;
if (head == NULL) return NULL; //EMPTY LIST
why2_node_t *buffer = head;
while (buffer -> next != NULL)
{
if (buffer -> value == value) return buffer;
buffer = buffer -> next;
}
if (value != buffer -> value) buffer = NULL; //PREVENT FROM RETURNING INVALID NODE
return buffer;
}
unsigned long why2_list_get_size(why2_list_t *list)
{
unsigned long n = 0; //RETURNING SIZE
why2_node_t *head = list -> head;
if (head == NULL) return n; //EMPTY LIST
why2_node_t *buffer = head;
do
{
n++;
buffer = buffer -> next; //ITER
} while (buffer != NULL);
return n;
}

View File

@ -1,21 +1,3 @@
/*
This is part of WHY2
Copyright (C) 2022 Václav Šmejkal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/* /*
bro this whole file is fucked up af... bro this whole file is fucked up af...
@ -73,8 +55,6 @@ void push_to_list(void *pointer, enum POINTER_TYPES type)
void remove_node(node_t *node) void remove_node(node_t *node)
{ {
if (node == NULL) return; //NULL NODE
node_t *buffer_1 = head; node_t *buffer_1 = head;
node_t *buffer_2; node_t *buffer_2;
@ -108,7 +88,7 @@ void remove_node(node_t *node)
node_t *get_node(void *pointer) node_t *get_node(void *pointer)
{ {
if (head == NULL || pointer == NULL) return NULL; //EMPTY LIST if (head == NULL) return NULL; //EMPTY LIST
node_t *buffer = head; node_t *buffer = head;
while (buffer -> next != NULL) while (buffer -> next != NULL)
@ -191,8 +171,6 @@ void *why2_opendir(char *name)
void why2_deallocate(void *pointer) void why2_deallocate(void *pointer)
{ {
if (pointer == NULL) return; //DEALLOCATING NULL
//VARIABLES //VARIABLES
node_t *node = get_node(pointer); node_t *node = get_node(pointer);
@ -240,9 +218,4 @@ void why2_clean_memory(char *identifier)
if (buffer -> identifier == identifier || force_deallocating) why2_deallocate(buffer -> pointer); //LAST NODE if (buffer -> identifier == identifier || force_deallocating) why2_deallocate(buffer -> pointer); //LAST NODE
why2_reset_memory_identifier(); //THIS WILL CAUSE SEGFAULT IF YOU DIDN'T USE why2_set_memory_identifier why2_reset_memory_identifier(); //THIS WILL CAUSE SEGFAULT IF YOU DIDN'T USE why2_set_memory_identifier
}
why2_bool why2_allocated(void *pointer)
{
return get_node(pointer) != NULL;
} }

View File

@ -20,11 +20,9 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <why2/misc.h> #include <why2/misc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h> #include <string.h>
#include <unistd.h> #include <unistd.h>
#include <sys/random.h> #include <sys/time.h>
#include <ftw.h> #include <ftw.h>
#include <curl/curl.h> #include <curl/curl.h>
@ -34,9 +32,11 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <why2/flags.h> #include <why2/flags.h>
#include <why2/memory.h> #include <why2/memory.h>
int multiply_cb(int a, int b) { return a * b; } why2_bool seedSet = 0; //DO NOT FUCKING TOUCH THIS!!!
int subtract_cb(int a, int b) { return a - b; }
int sum_cb(int a, int b) { return a + b; } double multiply_cb(int a, int b) { return a * b; }
double subtract_cb(int a, int b) { return a - b; }
double sum_cb(int a, int b) { return a + b; }
int unlink_cb(const char *fpath, WHY2_UNUSED const struct stat *sb, WHY2_UNUSED int typeflag, WHY2_UNUSED struct FTW *ftwbuf) int unlink_cb(const char *fpath, WHY2_UNUSED const struct stat *sb, WHY2_UNUSED int typeflag, WHY2_UNUSED struct FTW *ftwbuf)
{ {
@ -52,19 +52,40 @@ int removeDirectory(char *path)
return nftw(path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS); return nftw(path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
} }
void why2_directory(void) char *replaceWord(char *string, char *old, char *new) //CODE FROM: https://www.geeksforgeeks.org/c-program-replace-word-text-another-given-word
{ {
struct stat st; char *result;
char *buffer = why2_replace(WHY2_CONFIG_DIR, "{USER}", getenv("USER")); int i, cnt = 0;
int newLen = strlen(new);
int oldLen = strlen(old);
//CREATE USER CONFIG FOLDER for (i = 0; string[i] != '\0'; i++)
if (stat(buffer, &st) == -1)
{ {
mkdir(buffer, 0700); if (strstr(&string[i], old) == &string[i])
{
cnt++;
i += oldLen - 1;
}
} }
//DEALLOCATION result = (char*) why2_malloc(i + cnt * (newLen - oldLen) + 1);
why2_deallocate(buffer);
i = 0;
while (*string)
{
// compare the substring with the result
if (strstr(string, old) == string)
{
strcpy(&result[i], new);
i += newLen;
string += oldLen;
}
else result[i++] = *string++;
}
result[i] = '\0';
return result;
} }
enum WHY2_EXIT_CODES why2_check_version(void) enum WHY2_EXIT_CODES why2_check_version(void)
@ -72,21 +93,17 @@ enum WHY2_EXIT_CODES why2_check_version(void)
if (why2_get_flags().no_check) return WHY2_SUCCESS; if (why2_get_flags().no_check) return WHY2_SUCCESS;
why2_set_memory_identifier("core_version_check"); why2_set_memory_identifier("core_version_check");
why2_directory(); //MAKE SURE WHY2 DIR EXISTS
//FILE-CHECK VARIABLES //FILE-CHECK VARIABLES
int not_found_buffer = 0; int notFoundBuffer = 0;
//GET VERSION FILE
char *version_file = why2_replace(WHY2_VERSIONS_NAME, "{USER}", getenv("USER"));
//CURL VARIABLES //CURL VARIABLES
CURL *curl = curl_easy_init(); CURL *curl = curl_easy_init();
FILE *file_buffer = why2_fopen(version_file, "w+"); FILE *fileBuffer = why2_fopen(WHY2_VERSIONS_NAME, "w+");
//GET versions.json //GET versions.json
curl_easy_setopt(curl, CURLOPT_URL, WHY2_VERSIONS_URL); curl_easy_setopt(curl, CURLOPT_URL, WHY2_VERSIONS_URL);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, file_buffer); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fileBuffer);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, WHY2_CURL_TIMEOUT); curl_easy_setopt(curl, CURLOPT_TIMEOUT, WHY2_CURL_TIMEOUT);
//DOWNLOAD versions.json //DOWNLOAD versions.json
@ -94,50 +111,49 @@ enum WHY2_EXIT_CODES why2_check_version(void)
//CLEANUP //CLEANUP
curl_easy_cleanup(curl); curl_easy_cleanup(curl);
why2_deallocate(file_buffer); why2_deallocate(fileBuffer);
while (access(version_file, R_OK) != 0) while (access(WHY2_VERSIONS_NAME, R_OK) != 0)
{ {
not_found_buffer++; notFoundBuffer++;
if (not_found_buffer == WHY2_NOT_FOUND_TRIES) if (notFoundBuffer == WHY2_NOT_FOUND_TRIES)
{ {
if (!why2_get_flags().no_output) fprintf(stderr, "%s'%s' not found! Exiting...\n", WHY2_CLEAR_SCREEN, version_file); if (!why2_get_flags().no_output) fprintf(stderr, "%s'%s' not found! Exiting...\n", WHY2_CLEAR_SCREEN, WHY2_VERSIONS_NAME);
why2_clean_memory("core_version_check"); why2_clean_memory("core_version_check");
return WHY2_DOWNLOAD_FAILED; return WHY2_DOWNLOAD_FAILED;
} }
if (!why2_get_flags().no_output) printf("%s'%s' not found (%dx)! Trying again in a second.\n", WHY2_CLEAR_SCREEN, version_file, not_found_buffer); if (!why2_get_flags().no_output) printf("%s'%s' not found (%dx)! Trying again in a second.\n", WHY2_CLEAR_SCREEN, WHY2_VERSIONS_NAME, notFoundBuffer);
sleep(1); sleep(1);
} }
//JSON VARIABLES //JSON VARIABLES
char *buffer; char *buffer;
long buffer_size; struct json_object *parsedJson;
struct json_object *parsed_json;
struct json_object *active; struct json_object *active;
int bufferSize;
//COUNT LENGTH OF buffer AND STORE IT IN bufferSize //COUNT LENGTH OF buffer AND STORE IT IN bufferSize
file_buffer = why2_fopen(version_file, "r"); fileBuffer = why2_fopen(WHY2_VERSIONS_NAME, "r");
fseek(file_buffer, 0, SEEK_END); fseek(fileBuffer, 0, SEEK_END);
buffer_size = ftell(file_buffer); bufferSize = ftell(fileBuffer);
rewind(file_buffer); //REWIND file_buffer (NO SHIT) rewind(fileBuffer); //REWIND fileBuffer (NO SHIT)
//SET LENGTH OF buffer //SET LENGTH OF buffer
buffer = why2_calloc(buffer_size + 1, sizeof(char)); buffer = why2_calloc(bufferSize + 1, sizeof(char));
//LOAD jsonFile //LOAD jsonFile
if (fread(buffer, buffer_size, 1, file_buffer) != 1) if (fread(buffer, bufferSize, 1, fileBuffer) != 1)
{ {
if (!why2_get_flags().no_output) fprintf(stderr, "Reading file failed!\n"); if (!why2_get_flags().no_output) fprintf(stderr, "Reading file failed!\n");
// BELOW CODE IS COMMENTED OUT, BECAUSE IT IS PROBABLY UNNECESSARY why2_clean_memory("core_version_check");
// why2_clean_memory("core_version_check"); return WHY2_DOWNLOAD_FAILED;
// return WHY2_DOWNLOAD_FAILED;
} }
buffer[buffer_size] = '\0'; buffer[bufferSize] = '\0';
//CHECK FOR TEXT IN buffer //CHECK FOR TEXT IN buffer
if (strcmp(buffer, "") == 0) if (strcmp(buffer, "") == 0)
@ -152,11 +168,11 @@ enum WHY2_EXIT_CODES why2_check_version(void)
} }
//CLEANUP //CLEANUP
why2_deallocate(file_buffer); why2_deallocate(fileBuffer);
//GET //GET
parsed_json = json_tokener_parse(buffer); //yes, ik, i could use json_object_from_file, but I need to check for internet somehow parsedJson = json_tokener_parse(buffer); //yes, ik, i could use json_object_from_file, but I need to check for internet somehow
json_object_object_get_ex(parsed_json, "active", &active); json_object_object_get_ex(parsedJson, "active", &active);
if (strcmp(WHY2_VERSION, json_object_get_string(active)) != 0) if (strcmp(WHY2_VERSION, json_object_get_string(active)) != 0)
{ {
@ -175,8 +191,8 @@ enum WHY2_EXIT_CODES why2_check_version(void)
//VARIABLES //VARIABLES
git_repository *repo = NULL; git_repository *repo = NULL;
int exit_code; int exit_code;
char *install_command; char *installCommand;
int install_code; int installCode;
//MESSAGE //MESSAGE
if (!why2_get_flags().no_output) printf("Your WHY2 version is outdated!\nUpdating...\t[BETA]\n\n"); if (!why2_get_flags().no_output) printf("Your WHY2 version is outdated!\nUpdating...\t[BETA]\n\n");
@ -202,114 +218,99 @@ enum WHY2_EXIT_CODES why2_check_version(void)
return WHY2_WHY2_UPDATE_FAILED; return WHY2_WHY2_UPDATE_FAILED;
} }
//COUNT install_command LENGTH & ALLOCATE IT //COUNT installCommand LENGTH & ALLOCATE IT
install_command = why2_replace(WHY2_UPDATE_COMMAND, "{DIR}", WHY2_UPDATE_NAME); installCommand = replaceWord(WHY2_UPDATE_COMMAND, "{DIR}", WHY2_UPDATE_NAME);
install_code = system(install_command); //INSTALL installCode = system(installCommand); //INSTALL
//REMOVE versions.json - OTHERWISE WILL CAUSE SEGFAULT IN NEXT RUN //REMOVE versions.json - OTHERWISE WILL CAUSE SEGFAULT IN NEXT RUN
remove(version_file); remove(WHY2_VERSIONS_NAME);
why2_deallocate(install_command); why2_deallocate(installCommand);
//CHECK FOR ERRORS //CHECK FOR ERRORS
if (install_code != 0) if (installCode != 0)
{ {
if (!why2_get_flags().no_output) fprintf(stderr, "Updating failed! (installing)\n"); if (!why2_get_flags().no_output) fprintf(stderr, "Updating failed! (installing)\n");
why2_clean_memory("core_version_check"); why2_clean_memory("core_version_check");
return WHY2_WHY2_UPDATE_FAILED; return WHY2_WHY2_UPDATE_FAILED;
} }
} else
goto deallocation; //GREAT SUCCESS!
}
//COUNT WHY2_VERSIONS BEHIND
int versionsIndex = -1;
int versionsBuffer = 0;
struct json_object *deprecated;
json_object_object_get_ex(parsedJson, "deprecated", &deprecated);
//COUNT versionsIndex
for (int i = 0; i < (int) json_object_array_length(deprecated); i++)
{ {
//COUNT WHY2_VERSIONS BEHIND //IT'S A MATCH, BABY :D
int versions_index = -1; if (strcmp(json_object_get_string(json_object_array_get_idx(deprecated, i)), WHY2_VERSION) == 0)
int versions_buffer = 0;
struct json_object *deprecated;
json_object_object_get_ex(parsed_json, "deprecated", &deprecated);
//COUNT versions_index
for (int i = 0; i < (int) json_object_array_length(deprecated); i++)
{ {
//IT'S A MATCH, BABY :D versionsIndex = i;
if (strcmp(json_object_get_string(json_object_array_get_idx(deprecated, i)), WHY2_VERSION) == 0)
{
versions_index = i;
break; break;
}
}
//versions.json DOESN'T CONTAIN WHY2_VERSION (THIS WILL NOT HAPPEN IF YOU WILL NOT EDIT IT)
if (versions_index == -1)
{
if (!why2_get_flags().no_output) printf("Version %s not found! Check your flags.\n\n", WHY2_VERSION);
} else
{
//COUNT versions_buffer
versions_buffer = json_object_array_length(deprecated) - versions_index;
if (!why2_get_flags().no_output) fprintf(stderr, "This release could be unsafe! You're %d versions behind! (%s/%s)\n\n", versions_buffer, WHY2_VERSION, json_object_get_string(active));
//WAIT FOR 5 SECONDS
sleep(5);
} }
} }
//versions.json DOESN'T CONTAIN WHY2_VERSION (THIS WILL NOT HAPPEN IF YOU WILL NOT EDIT IT)
if (versionsIndex == -1)
{
if (!why2_get_flags().no_output) printf("Version %s not found! Check your flags.\n\n", WHY2_VERSION);
goto deallocation;
}
//COUNT versionsBuffer
versionsBuffer = json_object_array_length(deprecated) - versionsIndex;
if (!why2_get_flags().no_output) fprintf(stderr, "This release could be unsafe! You're %d versions behind! (%s/%s)\n\n", versionsBuffer, WHY2_VERSION, json_object_get_string(active));
//WAIT FOR 5 SECONDS
sleep(5);
} }
deallocation:
//DEALLOCATION //DEALLOCATION
json_object_put(parsed_json); //THIS FREES EVERY json_object - AT LEAST JSON-C'S DOCUMENTATION SAYS THAT json_object_put(parsedJson); //THIS FREES EVERY json_object - AT LEAST JSON-C'S DOCUMENTATION SAYS THAT
why2_deallocate(buffer); why2_deallocate(buffer);
why2_deallocate(version_file);
why2_reset_memory_identifier(); why2_reset_memory_identifier();
return WHY2_SUCCESS; return WHY2_SUCCESS;
} }
void why2_generate_text_key_chain(char *key, int *text_key_chain, int text_key_chain_size) void why2_generate_text_key_chain(char *key, int *textKeyChain, int textKeyChainSize)
{ {
int number_buffer; int numberBuffer;
int number_buffer_2 = 0; int numberBuffer2;
int number_buffer_3 = 0; double (*cb)(int, int);
int (*cb)(int, int);
for (int i = 0; i < text_key_chain_size; i++) for (int i = 0; i < textKeyChainSize; i++)
{ {
number_buffer = i; numberBuffer = i;
//CHECK, IF number_buffer ISN'T GREATER THAN keyLength AND CUT WHY2_UNUSED LENGTH //CHECK, IF numberBuffer ISN'T GREATER THAN keyLength AND CUT WHY2_UNUSED LENGTH
while (number_buffer >= (int) why2_get_key_length()) while (numberBuffer >= (int) why2_get_key_length())
{ {
number_buffer -= why2_get_key_length(); numberBuffer -= why2_get_key_length();
} }
//SET tkch VERSION numberBuffer2 = why2_get_key_length() - (numberBuffer + (i < textKeyChainSize));
switch (why2_get_flags().version)
{
case WHY2_v1:
number_buffer_2 = i;
number_buffer_3 = number_buffer + (i < text_key_chain_size);
break;
case WHY2_v2:
number_buffer_2 = i;
number_buffer_3 = why2_get_key_length() - (number_buffer + (i < text_key_chain_size));
break;
case WHY2_v3:
number_buffer_2 = text_key_chain_size - (i + 1);
number_buffer_3 = why2_get_key_length() - (number_buffer + (i < text_key_chain_size));
break;
}
//FILL textKeyChain //FILL textKeyChain
if ((number_buffer + 1) % 3 == 0) if ((numberBuffer + 1) % 3 == 0)
{ {
cb = multiply_cb; cb = multiply_cb;
} }
else if ((number_buffer + 1) % 2 == 0) else if ((numberBuffer + 1) % 2 == 0)
{ {
cb = subtract_cb; cb = subtract_cb;
} }
@ -318,7 +319,7 @@ void why2_generate_text_key_chain(char *key, int *text_key_chain, int text_key_c
cb = sum_cb; cb = sum_cb;
} }
text_key_chain[number_buffer_2] = cb(key[number_buffer], key[number_buffer_3]); textKeyChain[textKeyChainSize - (i + 1)] = cb(key[numberBuffer], key[numberBuffer2]);
} }
} }
@ -411,83 +412,57 @@ unsigned long why2_compare_time_micro(struct timeval startTime, struct timeval f
char *why2_generate_key(int key_length) char *why2_generate_key(int key_length)
{ {
int number_buffer; int numberBuffer;
unsigned int random_buffer;
char *key; char *key;
if (!seedSet)
{
why2_set_memory_identifier("core_key_generation_random");
//TRY TO MAKE RANDOM GENERATION REALLY "RANDOM"
FILE *fileBuffer;
fileBuffer = why2_fopen("/dev/urandom", "r");
if (fread(&numberBuffer, sizeof(numberBuffer), 1, fileBuffer) != 1)
{
if (!why2_get_flags().no_output) fprintf(stderr, "Reading file failed!\n");
why2_clean_memory("core_key_generation_random");
return NULL;
}
numberBuffer = abs(numberBuffer); //MAKE numberBuffer POSITIVE
srand(numberBuffer);
why2_deallocate(fileBuffer);
seedSet = 1;
why2_reset_memory_identifier();
}
key = why2_malloc(key_length + 1); key = why2_malloc(key_length + 1);
for (int i = 0; i < key_length; i++) for (int i = 0; i < key_length; i++)
{ {
//GET RANDOM NUMBER
if (getrandom(&random_buffer, sizeof(unsigned int), GRND_NONBLOCK) == -1) why2_die("getrandom fn failed!");
//SET numberBuffer TO RANDOM NUMBER BETWEEN 0 AND 52 //SET numberBuffer TO RANDOM NUMBER BETWEEN 0 AND 52
number_buffer = (random_buffer % 52) + 1; numberBuffer = (rand() % 52) + 1;
//GET CHAR FROM numberBuffer //GET CHAR FROM numberBuffer
if (number_buffer > 26) if (numberBuffer > 26)
{ {
number_buffer += 70; numberBuffer += 70;
} else }
else
{ {
number_buffer += 64; numberBuffer += 64;
} }
key[i] = (char) number_buffer; key[i] = (char) numberBuffer;
} }
key[key_length] = '\0'; key[key_length] = '\0';
return key; return key;
}
void why2_die(char *exit_msg)
{
fprintf(stderr, "%s\n", exit_msg); //ERR MSG
why2_clean_memory(why2_get_default_memory_identifier()); //GARBAGE COLLECTOR
exit(1);
}
char *why2_replace(char *string, char *old, char *new) //CODE FROM: https://www.geeksforgeeks.org/c-program-replace-word-text-another-given-word
{
char *result;
int i, cnt = 0;
int newLen = strlen(new);
int oldLen = strlen(old);
for (i = 0; string[i] != '\0'; i++)
{
if (strstr(&string[i], old) == &string[i])
{
cnt++;
i += oldLen - 1;
}
}
result = (char*) why2_malloc(i + cnt * (newLen - oldLen) + 1);
i = 0;
while (*string)
{
// compare the substring with the result
if (strstr(string, old) == string)
{
strcpy(&result[i], new);
i += newLen;
string += oldLen;
}
else result[i++] = *string++;
}
result[i] = '\0';
return result;
}
unsigned short why2_byte_format_length(char *s)
{
return ((s[1] - 1) << 7) | (s[0] - 1); //ADD THE FIRST TWO INDEXES TOGETHER TO GET LENGTH
} }

View File

@ -15,9 +15,7 @@ int main(void)
{ {
1, 1,
1, 1,
0, 0
WHY2_v3,
WHY2_OUTPUT_TEXT
} }
); );

View File

@ -71,29 +71,32 @@ why2_log_file why2_init_logger(char *directoryPath)
if (buffer > WHY2_MAX_USAGE) //WHY2_MAX_USAGE WAS REACHED if (buffer > WHY2_MAX_USAGE) //WHY2_MAX_USAGE WAS REACHED
{ {
file = INVALID_FILE; file = INVALID_FILE;
} else
{
sprintf(filePath, WHY2_LOG_FORMATTING, directoryPath, dateBuffer, buffer); //GENERATE LOG-NAME
file = open(filePath, O_RDWR | O_APPEND | O_CREAT, 0644); //CREATE LOG FILE goto deallocation;
//CREATE SYMLINK
sprintf(latestBuffer, WHY2_LOG_LATEST_FORMATTING, directoryPath, WHY2_LOG_LATEST); //GENERATE LATEST.log PATH
latestFilePath = why2_strdup(filePath);
if (access(latestBuffer, R_OK) == 0) { unlink(latestBuffer); } //REMOVE SYMLINK IF IT ALREADY EXISTS
if (symlink(latestFilePath + (strlen(directoryPath) + 1), latestBuffer) != 0) //CREATE SYMLINK
{
if (!why2_get_flags().no_output) fprintf(stderr, "Creating symlink failed!\n");
close(file);
why2_clean_memory("logger_logfile_init");
return why2_empty_log_file();
}
} }
sprintf(filePath, WHY2_LOG_FORMATTING, directoryPath, dateBuffer, buffer); //GENERATE LOG-NAME
file = open(filePath, O_RDWR | O_APPEND | O_CREAT, 0644); //CREATE LOG FILE
//CREATE SYMLINK
sprintf(latestBuffer, WHY2_LOG_LATEST_FORMATTING, directoryPath, WHY2_LOG_LATEST); //GENERATE LATEST.log PATH
latestFilePath = why2_strdup(filePath);
if (access(latestBuffer, R_OK) == 0) { unlink(latestBuffer); } //REMOVE SYMLINK IF IT ALREADY EXISTS
if (symlink(latestFilePath + (strlen(directoryPath) + 1), latestBuffer) != 0) //CREATE SYMLINK
{
if (!why2_get_flags().no_output) fprintf(stderr, "Creating symlink failed!\n");
close(file);
why2_clean_memory("logger_logfile_init");
return why2_empty_log_file();
}
deallocation:
//DEALLOCATION //DEALLOCATION
why2_deallocate(dateBuffer); why2_deallocate(dateBuffer);
why2_deallocate(latestBuffer); why2_deallocate(latestBuffer);
@ -132,7 +135,7 @@ void why2_write_log(int loggerFile, char *logMessage)
why2_log_flags flags = why2_get_log_flags(); why2_log_flags flags = why2_get_log_flags();
//SET ENCRYPTER FLAGS //SET ENCRYPTER FLAGS
if (!why2_get_flags_changed()) why2_set_flags((why2_input_flags) { 0, 1, 0, WHY2_v3, WHY2_OUTPUT_TEXT }); if (!why2_get_flags_changed()) why2_set_flags((why2_input_flags) { 0, 1, 0 });
if (flags.key != NULL) //ENCRYPT TEXT IF KEY WAS CHANGED if (flags.key != NULL) //ENCRYPT TEXT IF KEY WAS CHANGED
{ {