Compare commits

..

1 Commits

Author SHA1 Message Date
e43f0fe55c
changed encryption style to xor instead of minus
[WARNING] This is just test, I recommend using default (stable) branch... But ofc you don't have to listen to me lmao
2022-10-12 19:58:05 +02:00
56 changed files with 1009 additions and 5434 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

@ -1,74 +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: Test WHY2-core
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
output: ./out/why2-core-test
valgrind: valgrind --leak-check=full --show-leak-kinds=reachable --track-origins=yes -s
configure: configure.sh
app: why2
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 Valgrind
run: sudo apt install valgrind
- name: Install WHY2
run: make install
- name: Build WHY2 Test
run: make test_core
- name: Test Lib
run: ./${{ matrix.output }}
- name: Test App
run: ${{ matrix.app }}
- name: Test Lib by Valgrind
run: ${{ matrix.valgrind }} ${{ matrix.output }}

View File

@ -1,74 +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: Test WHY2-logger
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
output: ./out/why2-logger-test
configure: configure.sh
valgrind: valgrind --leak-check=full --show-leak-kinds=reachable --track-origins=yes -s
app: why2-logger
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 Valgrind
run: sudo apt install valgrind
- name: Install WHY2
run: make install
- name: Build WHY2 Test
run: make test_logger
- name: Test Lib
run: ./${{ matrix.output }}
- name: Test App
run: ${{ matrix.app }}
- name: Test Lib by Valgrind
run: ${{ matrix.valgrind }} ${{ matrix.output }}

View File

@ -1,19 +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/>.
name: Test Project name: Test Project
on: on:
@ -53,10 +37,10 @@ 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 -L -o ${{ matrix.test }}.c https://gist.github.com/ENGO150/d8419b6c31ffb68ebb930a5b41af8c73/raw
- name: Build WHY2 project - name: Build WHY2 project
run: cc ${{ matrix.test }}.c -lwhy2 -Wall -o ${{ matrix.test }} run: cc ${{ matrix.test }}.c -lwhy2 -Wall -o ${{ matrix.test }}

49
.github/workflows/why2-test.yml vendored Normal file
View File

@ -0,0 +1,49 @@
name: Test WHY2
on:
push:
branches: [ development ]
workflow_dispatch:
jobs:
test-why2:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ ubuntu-latest ]
include:
- os: ubuntu-latest
output: out/why2-test
configure: configure.sh
app: why2
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: sudo make install
- name: Build WHY2 Test
run: make test
- name: Test Lib
run: ./${{ matrix.output }}
- name: Test App
run: ${{ matrix.app }}

6
.gitignore vendored
View File

@ -1,8 +1,4 @@
.vscode/ .vscode/
.ccls-cache/ .ccls-cache/
out/ out/
misc/ misc/
logs/
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.

160
Makefile
View File

@ -1,68 +1,20 @@
# 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/>.
# Compiler Settings # Compiler Settings
CC=cc CC=cc
RC=cargo CFLAGS=-Wall -Wextra -Werror -Wcomment -Wformat -Wformat-security -Wmain -Wnonnull -Wunused -std=c11
CP=sudo install -m 755 # Not so compiler related but idk where to put it
RFLAGS=--manifest-path src/chat/config/Cargo.toml # Source Code
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 SRC=src/lib/*.c
SRC_APP=src/app/*.c
INCLUDE_DIR=include
INCLUDE=$(INCLUDE_DIR)/*.h
TEST=src/lib/test/main.c
LIBS=-ljson-c -lcurl -lgit2
# Output Files # Output Files
PROJECT_NAME=why2 PROJECT_NAME=why2
OUTPUT=out OUTPUT=out
LOGS=logs OUTPUT_TEST=$(OUTPUT)/$(PROJECT_NAME)-test
OUTPUT_APP=$(OUTPUT)/$(PROJECT_NAME)-app
OUTPUT_TEST_CORE=$(OUTPUT)/$(PROJECT_NAME)-core-test
OUTPUT_APP_CORE=$(OUTPUT)/$(PROJECT_NAME)-core-app
OUTPUT_TEST_LOGGER=$(OUTPUT)/$(PROJECT_NAME)-logger-test
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
SRC_CORE=./src/core/lib/*.c ./src/core/lib/utils/*.c
SRC_CORE_APP=./src/core/app/*.c
SRC_LOGGER=./src/logger/lib/*.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_CORE=$(INCLUDE_DIR)/*.h
INCLUDE_LOGGER=$(INCLUDE_DIR)/logger/*.h
INCLUDE_CHAT=$(INCLUDE_DIR)/chat/*.h
TEST_CORE=./src/core/lib/test/main.c
LIBS_CORE=-ljson-c -lcurl -lgit2
LIB_CORE=-l$(PROJECT_NAME)
TEST_LOGGER=./src/logger/lib/test/main.c
LIBS_LOGGER=$(LIB_CORE)
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
@ -74,86 +26,30 @@ 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: installHeader:
ifneq ($(BYPASS_CHECK),true) for file in $(INCLUDE); do install -m 755 -D $(DOLLAR)file -t $(INSTALL_INCLUDE)/$(PROJECT_NAME); done
@if [ "$(shell id -u)" = 0 ]; then\ install -m 755 $(INCLUDE_DIR)/$(PROJECT_NAME).h $(INSTALL_INCLUDE)/$(PROJECT_NAME).h
echo "Do not run install rules as root.";\
exit 1;\
fi
endif
install_header_core: installLib:
for file in $(INCLUDE_CORE); do $(CP) -D $(DOLLAR)file -t $(INSTALL_INCLUDE)/$(PROJECT_NAME); done $(CC) $(CFLAGS) -fPIC -c $(SRC)
sudo ln -sf $(INSTALL_INCLUDE)/$(PROJECT_NAME)/$(PROJECT_NAME).h $(INSTALL_INCLUDE)/$(PROJECT_NAME).h $(CC) $(CFLAGS) -shared -o lib$(PROJECT_NAME).so *.o $(LIBS)
install -m 755 lib$(PROJECT_NAME).so $(INSTALL_LIBRARY)/lib$(PROJECT_NAME).so
install_header_logger: installApp: app
for file in $(INCLUDE_LOGGER); do $(CP) -D $(DOLLAR)file -t $(INSTALL_INCLUDE)/$(PROJECT_NAME)/logger; done install -m 755 $(OUTPUT_APP) $(INSTALL_BIN)/$(PROJECT_NAME)
install_header_chat: test:
for file in $(INCLUDE_CHAT); do $(CP) -D $(DOLLAR)file -t $(INSTALL_INCLUDE)/$(PROJECT_NAME)/chat; done $(CC) $(CFLAGS) -g $(TEST) -o $(OUTPUT_TEST) -l$(PROJECT_NAME)
build_lib_core: app:
$(MAKE) clean $(CC) $(CFLAGS) $(SRC_APP) -o $(OUTPUT_APP) -l$(PROJECT_NAME)
$(CC) $(CFLAGS) -fPIC -c $(SRC_CORE)
$(CC) $(CFLAGS) -shared -o lib$(PROJECT_NAME).so *.o $(LIBS_CORE)
build_lib_logger:
$(MAKE) clean
$(CC) $(CFLAGS) -fPIC -c $(SRC_LOGGER)
$(CC) $(CFLAGS) -shared -o lib$(PROJECT_NAME)-logger.so *.o $(LIBS_LOGGER)
build_chat_client:
$(CC) $(CFLAGS) $(SRC_CHAT_CLIENT) -o $(OUTPUT_CHAT_CLIENT) $(LIBS_CHAT)
build_chat_server:
$(CC) $(CFLAGS) $(SRC_CHAT_SERVER) -o $(OUTPUT_CHAT_SERVER) $(LIBS_CHAT)
build_lib_chat:
$(MAKE) clean
$(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
$(CP) ./lib$(PROJECT_NAME).so $(INSTALL_LIBRARY)/lib$(PROJECT_NAME).so
install_app_core: app_core
$(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)
test_logger:
$(CC) $(CFLAGS) $(TEST_LOGGER) -o $(OUTPUT_TEST_LOGGER) $(LIBS_LOGGER) $(LIB_LOGGER)
app_core:
$(CC) $(CFLAGS) $(SRC_CORE_APP) -o $(OUTPUT_APP_CORE) $(LIB_CORE)
app_logger:
$(CC) $(CFLAGS) $(SRC_LOGGER_APP) -o $(OUTPUT_APP_LOGGER) $(LIBS_LOGGER) $(LIB_LOGGER)
clean: clean:
$(RC) clean $(RFLAGS) rm -rf $(OUTPUT)/* *.o *.so
rm -rf $(OUTPUT)/* $(LOGS)/* *.o *.so vgcore.*
build_chat: build_chat_server build_chat_client install: installHeader installLib installApp clean
installTest: install test
install_header: install_header_core install_header_logger install_header_chat
install_libs: install_lib_core install_lib_logger install_lib_chat
install_apps: install_app_core install_app_logger
install: check_root install_header install_libs install_apps clean
install_test: install test_core test_logger
all: install all: install

53
configure.sh Executable file → Normal file
View File

@ -1,21 +1,5 @@
#!/bin/bash #!/bin/bash
# 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/>.
# Get linux distro # Get linux distro
DISTRO=$(lsb_release -is) DISTRO=$(lsb_release -is)
@ -24,43 +8,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

@ -1,34 +1,8 @@
/*
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_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 outputFlags decryptText(char *text, char *keyNew); //TEXT from WILL BE DECRYPTED WITH KEY AND RETURNED
#ifdef __cplusplus
}
#endif
#endif #endif

View File

@ -1,34 +1,8 @@
/*
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_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 outputFlags encryptText(char *text, char *keyNew); //TEXT from WILL BE ENCRYPTED WITH RANDOM PASSWORD [KEY] (WHICH WILL BE PRINTED OUT) AND RETURNED
#ifdef __cplusplus
}
#endif
#endif #endif

View File

@ -1,119 +1,65 @@
/*
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_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 const enum EXIT_CODES //exit codes you fucking idiot
{ {
WHY2_SUCCESS = 0, //EXIT CODE FOR WHY2_SUCCESSFUL RUN SUCCESS = 0, //EXIT CODE FOR SUCCESSFUL RUN
WHY2_INVALID_KEY = 1, //EXIT VALUE FOR INVALID KEY INVALID_KEY = 1, //EXIT VALUE FOR INVALID KEY
WHY2_INVALID_TEXT = 4, //EXIT VALUE FOR INVALID TEXT INVALID_TEXT = 4, //EXIT VALUE FOR INVALID TEXT
WHY2_DOWNLOAD_FAILED = 2, //EXIT VALUE FOR versions.json DOWNLOAD FAILED DOWNLOAD_FAILED = 2, //EXIT VALUE FOR versions.json DOWNLOAD FAILED
WHY2_WHY2_UPDATE_FAILED = 3 //EXIT VALUE FOR UPDATE FAILED UPDATE_FAILED = 3 //EXIT VALUE FOR UPDATE FAILED
}; };
#define VERSION "v4.3.2" //VERSION OF CURRENT BUILD > DO NOT TOUCH THIS <
#define VERSIONS_URL "https://raw.githubusercontent.com/ENGO150/WHY2/release/versions.json" //URL FOR GETTING versions.json
#define VERSIONS_NAME "/tmp/why2-versions.json" //do I have to explain this?
//THESE ARE 'HISTORIC' VERSION FOR GENERATING tkch, SO YOU CAN DECRYPT OLD TEXT #define UPDATE_URL "https://github.com/ENGO150/WHY2.git" // REPOSITORY URL FOR UPDATES (YOU DON'T SAY)
enum WHY2_TEXT_KEY_CHAIN_VERSIONS #define UPDATE_NAME "/tmp/why2-update" // fuck you
{ #define UPDATE_COMMAND "tmux new-session -d \"cd {DIR} && make install\""
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 #define TEST_TEXT "aAzZ( )!?#\\/śŠ <3|420*;㍿㊓ㅅΔ♛👶🏿" //TEST TEXT FOR ENCRYPTION IN why2-test BINARY
{
WHY2_OUTPUT_TEXT,
WHY2_OUTPUT_BYTE
};
#define WHY2_VERSION "v5.0" //WHY2_VERSION OF CURRENT BUILD > DO NOT TOUCH THIS < #define TEXT_TO_ENCRYPT "Some text yk" //THIS TEXT WILL BE ENCRYPTED IN why2-app BINARY
#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 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 CLEAR_SCREEN "\e[1;1H\e[2J" //TEXT FOR UNIX CLEAR SCREEN
#define WHY2_UPDATE_NAME "/tmp/why2-update" // fuck you
#define WHY2_UPDATE_COMMAND "tmux new-session -d \"cd {DIR} && make install\""
#define WHY2_TEST_TEXT "aAzZ( )!?#\\/śŠ <3|420*;㍿㊓ㅅΔ♛👶🏿" //TEST TEXT FOR ENCRYPTION IN why2-test BINARY #define CURL_TIMEOUT 3 //if you need comment explaining, what the fuck is timeout, don't change WHY2's code, alright? thx, love ya
#define NOT_FOUND_TRIES 10 //NUMBER OF TRIES FOR DOWNLOADING versions.json
#define WHY2_TEXT_TO_ENCRYPT "Some text yk" //THIS TEXT WILL BE ENCRYPTED IN why2-app BINARY #define DEPRECATED __attribute__((deprecated)) //SAME COMMENT AS VERSIONS_NAME'S
#define UNUSED __attribute__((unused)) //SAME COMMENT AS DEPRECATED'S
#define WHY2_CLEAR_SCREEN "\e[1;1H\e[2J" //TEXT FOR UNIX CLEAR SCREEN
#define WHY2_CURL_TIMEOUT 3 //if you need comment explaining, what the fuck is timeout, don't change WHY2's code, alright? thx, love ya
#define WHY2_NOT_FOUND_TRIES 10 //NUMBER OF TRIES FOR DOWNLOADING versions.json
#define WHY2_DEPRECATED __attribute__((deprecated)) //SAME COMMENT AS WHY2_VERSIONS_NAME'S
#define WHY2_UNUSED __attribute__((unused)) //SAME COMMENT AS WHY2_DEPRECATED'S
//TYPES
typedef _Bool why2_bool; //READ THE NAME OR I WILL FIND YOU AND FUCK YOUR MOTHERFUCKING DOG!!!
typedef int (*why2_encryption_operation_cb)(int, int); //TYPE FOR encryptionOperation CALLBACK
typedef struct
{
why2_bool no_check; //BOOLEAN FOR SKIPPING WHY2_VERSION CHECK
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
enum WHY2_TEXT_KEY_CHAIN_VERSIONS version; //VERSION OF tkch
enum WHY2_OUTPUT_FORMAT format; //VERSION OF tkch
} why2_input_flags;
typedef struct typedef struct
{ {
char *output_text; //VARIABLE FOR ENCRYPTED/DECRYPTED TEXT _Bool noCheck; //BOOLEAN FOR SKIPPING VERSION CHECK
char *used_key; //VARIABLE FOR USED/GENERATED KEY _Bool noOutput; //BOOLEAN FOR NOT PRINTING OUTPUT WHEN ENCRYPTING/DECRYPTING
unsigned long unused_key_size; //VARIABLE FOR COUNT OF WHY2_UNUSED CHARACTERS IN KEY _Bool update; //BOOLEAN FOR UPDATING YOUR WHY VERSION IF OLD IS USED
unsigned long repeated_key_size; //VARIABLE FOR COUNT OF REPEATED CHARACTERS IN KEY (basically reversed unused_key_size) } inputFlags;
unsigned long elapsed_time; //VARIABLE FOR ELAPSED TIME IN MICROSECONDS => 1s = 1000000µs
enum WHY2_EXIT_CODES exit_code; //VARIABLE FOR EXIT CODE typedef struct
} why2_output_flags; {
char *outputText; //VARIABLE FOR ENCRYPTED/DECRYPTED TEXT
char *usedKey; //VARIABLE FOR USED/GENERATED KEY
unsigned long unusedKeySize; //VARIABLE FOR COUNT OF UNUSED CHARACTERS IN KEY
unsigned long repeatedKeySize; //VARIABLE FOR COUNT OF REPEATED CHARACTERS IN KEY (basically reversed unusedKeySize)
unsigned long elapsedTime; //VARIABLE FOR ELAPSED TIME IN MICROSECONDS => 1s = 1000000µs
_Bool exitCode; //VARIABLE FOR EXIT CODE
} outputFlags;
//NOTE: Variables were moved to 'flags.c' to force y'all using getters //NOTE: Variables were moved to 'flags.c' to force y'all using getters
//GETTERS //GETTERS
char why2_get_encryption_separator(void); char getEncryptionSeparator();
unsigned long why2_get_key_length(void); unsigned long getKeyLength();
why2_input_flags why2_get_default_flags(void); //THIS GENERATES why2_input_flags WITH DEFAULT VALUES inputFlags defaultFlags(); //THIS GENERATES inputFlags WITH DEFAULT VALUES
why2_input_flags why2_get_flags(void); //RETURNS USED FLAGS inputFlags getFlags(); //RETURNS USED FLAGS
why2_output_flags why2_no_output(enum WHY2_EXIT_CODES exit_code); //SAME AS why2_get_default_flags() BUT FOR why2_output_flags outputFlags noOutput(_Bool exitCode); //SAME AS defaultFlags() BUT FOR outputFlags
why2_encryption_operation_cb why2_get_encryption_operation(void); //RETURNS FUNCTION WHICH IS USED FOR ENCRYPTION & DECRYPTION
why2_bool why2_get_flags_changed(void);
char *why2_get_memory_identifier(void); //RETURNS STRING USED IN LINKED LIST (IN memory.c) FOR IDENTIFYING NODES WHEN RUNNING GARBAGE COLLECTOR
char *why2_get_default_memory_identifier(void);
//SETTERS //SETTERS
void why2_set_encryption_separator(char encryption_separator_new); void setEncryptionSeparator(char encryptionSeparatorNew);
void why2_set_key_length(int keyLengthNew); void setKeyLength(int keyLengthNew);
void why2_set_flags(why2_input_flags newFlags); //.... whatcha think? void setFlags(inputFlags newFlags); //.... whatcha think?
void why2_set_encryption_operation(why2_encryption_operation_cb newEncryptionOperation); //are you that dumb?
void why2_set_memory_identifier(char *new_memory_identifier);
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

@ -1,83 +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_LOGGER_FLAGS_H
#define WHY2_LOGGER_FLAGS_H
#ifdef __cplusplus
extern "C" {
#endif
//CONSTS
enum WHY2_LOGGER_EXIT_CODES //exit codes you fucking idiot (2#)
{
INVALID_FILE = -1 //THIS WILL HAPPEN IF YOU USE TOO MUCH LOGS lol
};
#define WHY2_WRITE_MESSAGE_1 "Hello from logger-test! 👋"
#define WHY2_WRITE_MESSAGE_2 "aAzZ( )!?#\\/śŠ <3|420*;㍿㊓ㅅΔ♛👶🏿"
#define WHY2_WRITE_MESSAGE_3 "ˢᵃʸ ʸᵉˢ ᵗᵒ ᵈʳᵘᵍˢ"
#define WHY2_WRITE_DIR "./logs"
#define WHY2_LOG_LATEST "latest.log"
#define WHY2_TEST_DIRECTORY "/tmp"
#define WHY2_LOGGER_TEST_TEXT WHY2_WRITE_MESSAGE_3
#define WHY2_LOG_FORMAT "yyyy-mm-dd_xxx.log" //THE LAST xxx IS FOR BASE-16 NUMBER OF USAGE THAT DAY (SO MAX IS 4095 [FFF] USAGES PER DAY)
#define WHY2_LOG_FORMAT_START "yyyy-mm-dd" //FIRST PART OF WHY2_LOG_FORMAT
#define WHY2_LOG_FORMATTING "%s/%s_%03x.log" //SAME THING AS WHY2_LOG_FORMAT, BUT USED IN sprintf IN logger.c, NOT AS LENGTH
#define WHY2_LOG_FORMATTING_START "%04d-%02d-%02d" //FIRST PART OF WHY2_LOG_FORMATTING
#define WHY2_WRITE_FORMAT "[hh:mm:ss]: " //LOG MESSAGE'S PREFIX (THE SPACE AT THE END IS INTENTIONAL)
#define WHY2_WRITE_FORMATTING "[%02d:%02d:%02d]: %s\n" //guess what
#define WHY2_LOG_LATEST_FORMATTING "%s/%s"
#define WHY2_MAX_USAGE 0xfff //LOOK AT WHY2_LOG_FORMAT
//TYPES
typedef struct
{
int file;
char *filename;
} why2_log_file;
typedef struct
{
char *key;
} why2_log_flags;
typedef struct
{
char **decrypted_text;
unsigned long length;
} why2_decrypted_output;
//GETTERS
why2_log_flags why2_get_log_flags(void);
//SETTERS
void why2_set_log_flags(why2_log_flags why2_log_flagsNew);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -1,35 +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_LOGGER_LOGGER_H
#define WHY2_LOGGER_LOGGER_H
#ifdef __cplusplus
extern "C" {
#endif
#include <why2/logger/flags.h>
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
#ifdef __cplusplus
}
#endif
#endif

View File

@ -1,38 +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_LOGGER_UTILS_C
#define WHY2_LOGGER_UTILS_C
#ifdef __cplusplus
extern "C" {
#endif
#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_decrypted_output(why2_decrypted_output output); //DEALLOCATION OF POINTER-TO-POINTER, WHY TF ARE YOU READING THIS
why2_decrypted_output why2_decrypt_logger(why2_log_file logger); //PASS logger AND FLAGS, AND PROGRAM WILL DECRYPT YOUR LOG... WHAT 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!
#ifdef __cplusplus
}
#endif
#endif

View File

@ -1,48 +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_MEMORY_H
#define WHY2_MEMORY_H
#ifdef __cplusplus
extern "C" {
#endif
#include <why2/flags.h>
void *why2_malloc(unsigned long size);
void *why2_calloc(unsigned long element, unsigned long size);
void *why2_realloc(void *pointer, unsigned long size);
char *why2_strdup(char *string);
void *why2_fopen(char *name, char *modes);
void *why2_fdopen(int file, char *modes);
void *why2_opendir(char *name);
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
why2_bool why2_allocated(void *pointer); //CHECKS IF pointer WAS ALLOCATED USING WHY2-MEM
#ifdef __cplusplus
}
#endif
#endif

View File

@ -1,49 +1,18 @@
/*
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_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 generateTextKeyChain(char *key, int *textKeyChain, int textKeyChainSize); //GENERATES ARRAY FOR ENCRYPTION/DECRYPTION
char *why2_generate_key(int key_length); //GENERATE ENCRYPTION KEY void deallocateOutput(outputFlags flags); //DEALLOCATES flags
void why2_deallocate_output(why2_output_flags flags); //DEALLOCATES flags _Bool checkVersion(); //THIS FUNCTION CHECKS IF LATEST VERSION OF WHY2 IS USED
void why2_directory(void); //GENERATE WHY2_CONFIG_DIR _Bool checkKey(char *key); //CHECKS IF KEY IS VALID
enum WHY2_EXIT_CODES why2_check_version(void); //THIS FUNCTION CHECKS IF LATEST WHY2_VERSION OF WHY2 IS USED _Bool checkText(char *text); //CHECKS IF TEXT IS VALID
enum WHY2_EXIT_CODES why2_check_key(char *key); //CHECKS IF KEY IS VALID unsigned long countIntLength(int number); //RETURNS LENGTH OF number
enum WHY2_EXIT_CODES why2_check_text(char *text); //CHECKS IF TEXT IS VALID unsigned long countUnusedKeySize(char *text, char *key); //COUNT unusedKeySize
unsigned long why2_count_int_length(int number); //RETURNS LENGTH OF number unsigned long countRepeatedKeySize(char *text, char *key); //COUNT repeatedKeySize
unsigned long why2_count_unused_key_size(char *text, char *key); //COUNT unused_key_size unsigned long compareTimeMicro(struct timeval startTime, struct timeval finishTime); //COMPARE TIMES IN MICROSECONDS
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
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

@ -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/>.
*/
/* /*
This file basically contains all header files that are needed to use WHY2. This file basically contains all header files that are needed to use WHY2.
@ -25,31 +7,9 @@ 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
#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/misc.h> #include <why2/misc.h>
//LOGGER
#include <why2/logger/flags.h>
#include <why2/logger/logger.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

31
src/app/main.c Normal file
View File

@ -0,0 +1,31 @@
#include <stdio.h>
#include <why2.h>
int main(void)
{
//SET FLAGS
setFlags((inputFlags) {1, 1, 0});
//RUN ENCRYPTION WITH TEXT_TO_ENCRYPT, GENERATE NEW KEY AND DO NOT CHECK FOR ACTIVE VERSION & PREVENT ANY OUTPUT
outputFlags encryptedText = encryptText(TEXT_TO_ENCRYPT, NULL);
//SIMPLE TEXT
printf
(
"Hi.\n"
"This is a simple application written using WHY2 Encryption System.\n\n"
"\"%s\" => \"%s\"\n\n"
"If you'd like to know more about WHY2 Encryption System, please visit: https://github.com/ENGO150/WHY2/wiki \b\n"
"Thank you so much for supporting this project!\n"
, TEXT_TO_ENCRYPT, encryptedText.outputText
);
//DEALLOCATION
deallocateOutput(encryptedText);
return 0;
}

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

@ -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/>.
*/
#include <stdio.h>
#include <why2.h>
int main(void)
{
//SET FLAGS
why2_set_flags((why2_input_flags) { 1, 1, 0, WHY2_v3, WHY2_OUTPUT_TEXT });
//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);
//SIMPLE TEXT
printf
(
"Hi.\n"
"This is a simple application written using WHY2 Encryption System.\n\n"
"\"%s\" => \"%s\"\n\n"
"If you'd like to know more about WHY2 Encryption System, please visit: https://github.com/ENGO150/WHY2/wiki \b\n"
"Thank you so much for supporting this project!\n"
, WHY2_TEXT_TO_ENCRYPT, encryptedText.output_text
);
//DEALLOCATION
why2_deallocate_output(encryptedText);
return 0;
}

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/decrypter.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
#include <why2/flags.h>
#include <why2/memory.h>
#include <why2/misc.h>
why2_output_flags why2_decrypt_text(char *text, char *key_new)
{
//CHECK VARIABLE
unsigned char check_exit_code;
//TIME VARIABLES
struct timeval start_time;
struct timeval finish_time;
gettimeofday(&start_time, NULL);
//CHECK FOR ACTIVE WHY2_VERSION
if ((check_exit_code = why2_check_version()) != WHY2_SUCCESS)
{
return why2_no_output(check_exit_code);
}
//CHECK FOR INVALID text
if ((check_exit_code = why2_check_text(text)) != WHY2_SUCCESS)
{
return why2_no_output(check_exit_code);
}
//CHECK FOR INVALID key
if ((check_exit_code = why2_check_key(key_new)) != WHY2_SUCCESS)
{
return why2_no_output(check_exit_code);
}
//REDEFINE keyLength
why2_set_key_length(strlen(key_new));
//VARIABLES
char *returning_text;
int number_buffer = 0;
int used_text_deallocation_buffer = 0;
char *text_buffer = NULL;
int text_key_chainLength;
int *text_key_chain;
char *key = why2_strdup(key_new); //COPY key_new TO key
int *encrypted_text_key_chain;
char *used_text = NULL; //COPY text TO used_text
if (why2_get_flags().format == WHY2_OUTPUT_BYTE)
{
//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++)
{
if (used_text[i] == why2_get_encryption_separator()) number_buffer++;
}
//SET LENGTH (number_buffer)
returning_text = why2_calloc(number_buffer + 1, sizeof(char));
text_key_chain = why2_malloc(sizeof(int) * number_buffer);
encrypted_text_key_chain = why2_malloc(sizeof(int) * number_buffer);
text_key_chainLength = number_buffer;
//LOAD text_key_chain
why2_generate_text_key_chain(key, text_key_chain, number_buffer);
//LOAD encrypted_text_key_chain
for (int i = 0; i < text_key_chainLength; i++)
{
number_buffer = 0;
//GET LENGTH OF EACH CHARACTER
for (int j = 0; j < (int) strlen(used_text); j++)
{
if (used_text[j] == why2_get_encryption_separator()) break;
number_buffer++;
}
text_buffer = why2_realloc(text_buffer, number_buffer + 1);
//CLEAN (POSSIBLY EXISTING) JUNK in text_buffer
for (int j = 0; j <= number_buffer; j++)
{
text_buffer[j] = '\0';
}
//LOAD text_buffer
for (int j = 0; j < (int) strlen(used_text); j++)
{
text_buffer[j] = used_text[j];
if (number_buffer == j) break;
}
encrypted_text_key_chain[i] = atoi(text_buffer);
used_text += number_buffer + 1;
used_text_deallocation_buffer += number_buffer + 1;
}
//DECRYPT TEXT
for (int i = 0; i < text_key_chainLength; i++)
{
text_key_chain[i] = why2_get_encryption_operation()(text_key_chain[i], encrypted_text_key_chain[i]);
}
//LOAD returning_text
for (int i = 0; i < text_key_chainLength; i++)
{
returning_text[i] = text_key_chain[i];
}
//GET FINISH TIME
gettimeofday(&finish_time, NULL);
//LOAD output
why2_output_flags output =
{
returning_text, //DECRYPTED TEXT
key, //USED KEY
why2_count_unused_key_size(returning_text, key), // NUMBER OF WHY2_UNUSED CHARS IN KEY
why2_count_repeated_key_size(returning_text, key), //NUMBER OF REPEATED CHARS IN KEY
why2_compare_time_micro(start_time, finish_time), // ELAPSED TIME
WHY2_SUCCESS //EXIT CODE
};
//DEALLOCATION
why2_deallocate(text_key_chain);
why2_deallocate(encrypted_text_key_chain);
why2_deallocate(text_buffer);
why2_deallocate(used_text - used_text_deallocation_buffer);
return output;
}

View File

@ -1,161 +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/encrypter.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <why2/flags.h>
#include <why2/memory.h>
#include <why2/misc.h>
why2_output_flags why2_encrypt_text(char *text, char *key_new)
{
//CHECK VARIABLE
unsigned char check_exit_code;
//TIME VARIABLES
struct timeval start_time;
struct timeval finish_time;
gettimeofday(&start_time, NULL);
//CHECK FOR ACTIVE WHY2_VERSION
if ((check_exit_code = why2_check_version()) != WHY2_SUCCESS)
{
return why2_no_output(check_exit_code);
}
//CHECK FOR INVALID text
if ((check_exit_code = why2_check_text(text)) != WHY2_SUCCESS)
{
return why2_no_output(check_exit_code);
}
why2_set_memory_identifier("core_decrypt");
//VARIABLES
char *key = NULL;
char *returning_text = NULL;
char *text_buffer = NULL;
int *text_key_chain = why2_malloc(sizeof(int) * strlen(text));
int number_buffer = 0;
if (key_new != NULL)
{
//CHECK FOR INVALID key
if ((check_exit_code = why2_check_key(key_new)) != WHY2_SUCCESS)
{
why2_clean_memory("core_decrypt");
return why2_no_output(check_exit_code);
}
key = why2_strdup(key_new);
//REDEFINE keyLength
why2_set_key_length(strlen(key));
} else //LOAD KEY
{
key = why2_generate_key(why2_get_key_length());
}
//LOAD text_key_chain
why2_generate_text_key_chain(key, text_key_chain, strlen(text));
//ACTUALLY ENCRYPT TEXT
for (int i = 0; i < (int) strlen(text); i++)
{
text_key_chain[i] = why2_get_encryption_operation()(text_key_chain[i], (int) text[i]);
}
//OUTPUT FORMATS
if (why2_get_flags().format == WHY2_OUTPUT_TEXT) //NORMAL 420.-69 FORMAT
{
//COUNT REQUIRED SIZE FOR returning_text
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)
returning_text = why2_calloc(number_buffer + strlen(text), sizeof(char));
//LOAD returning_text
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
returning_text = why2_calloc(number_buffer + 1, sizeof(char)); //ALLOCATE
//SET LENGTH
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
for (unsigned long i = 0; i < strlen(text); i++)
{
//BUILD returning_text
returning_text[2 + (i * 2)] = text_key_chain[i] & 0x7f;
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++)
{
//ENSURE THERE IS NO \0
if (returning_text[j] == 0) returning_text[j] = -128;
}
}
}
//GET FINISH TIME
gettimeofday(&finish_time, NULL);
//LOAD output
why2_output_flags output =
{
returning_text, //ENCRYPTED TEXT
key, //GENERATED/USED 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_compare_time_micro(start_time, finish_time), // ELAPSED TIME
WHY2_SUCCESS //EXIT CODE
};
//DEALLOCATION
why2_deallocate(text_key_chain);
why2_deallocate(text_buffer);
why2_reset_memory_identifier();
return output;
}

View File

@ -1,162 +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/flags.h>
#include <stdlib.h>
#include <string.h>
#include <why2/llist.h>
#include <why2/memory.h>
//CONSTS (this is just local)
#define DEFAULT_FLAGS (why2_input_flags) { 0, 0, 0, WHY2_v3, WHY2_OUTPUT_TEXT }
#define DEFAULT_MEMORY_IDENTIFIER ""
int encryptionOperation(int text, int encryptedText);
//VARIABLES
char encryption_separator = '.'; //NOPE > DO NOT TOUCH THIS, USE why2_set_encryption_separator instead <
unsigned long keyLength = 50; //LENGTH OF KEY > DO NOT TOUCH THIS, USE why2_set_key_length instead <
why2_input_flags flagsAllah = DEFAULT_FLAGS; //IT IS CALLED flagsAllah CUZ flags CAUSED SOME FUCKING MEMORY PROBLEMS
why2_encryption_operation_cb encryptionOperation_cb = encryptionOperation;
why2_bool flagsChanged = 0; //CHANGES TO 1 WHEN U USE why2_set_flags
char *memory_identifier = DEFAULT_MEMORY_IDENTIFIER;
why2_list_t identifier_list = WHY2_LIST_EMPTY;
char *get_last_node_identifier(void)
{
if (identifier_list.head == NULL) return DEFAULT_MEMORY_IDENTIFIER;
why2_node_t *buffer = identifier_list.head;
while (buffer -> next != NULL) buffer = buffer -> next;
return buffer -> value;
}
//GETTERS
char why2_get_encryption_separator(void)
{
return encryption_separator;
}
unsigned long why2_get_key_length(void)
{
return keyLength;
}
why2_input_flags why2_get_default_flags(void)
{
return DEFAULT_FLAGS;
}
why2_input_flags why2_get_flags(void)
{
return flagsAllah;
}
why2_output_flags why2_no_output(enum WHY2_EXIT_CODES exit_code)
{
char *emptyText = why2_malloc(1); //TEXT
emptyText[0] = '\0';
char *emptyKey = why2_malloc(why2_get_key_length() + 1); //KEY
for (int i = 0; i < (int) why2_get_key_length(); i++)
{
emptyKey[i] = 'x';
}
emptyKey[why2_get_key_length()] = '\0';
return (why2_output_flags) { emptyText, emptyKey, 0, 0, 0, exit_code };
}
why2_encryption_operation_cb why2_get_encryption_operation(void)
{
return encryptionOperation_cb;
}
why2_bool why2_get_flags_changed(void)
{
return flagsChanged;
}
char *why2_get_memory_identifier(void)
{
return memory_identifier;
}
char *why2_get_default_memory_identifier(void)
{
return DEFAULT_MEMORY_IDENTIFIER;
}
//SETTERS
void why2_set_encryption_separator(char encryption_separator_new)
{
if
(
encryption_separator_new <= 31 ||
(encryption_separator_new >= 48 && encryption_separator_new <= 57) ||
encryption_separator_new == 45
) return;
encryption_separator = encryption_separator_new;
}
void why2_set_key_length(int keyLengthNew)
{
if (keyLengthNew < 1) return;
keyLength = keyLengthNew;
}
void why2_set_flags(why2_input_flags newFlags)
{
flagsAllah = newFlags;
if (!flagsChanged) flagsChanged = 1;
}
void why2_set_encryption_operation(why2_encryption_operation_cb newEncryptionOperation)
{
encryptionOperation_cb = newEncryptionOperation;
}
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
memory_identifier = new_memory_identifier;
}
void why2_reset_memory_identifier(void)
{
why2_list_remove_back(&identifier_list);
memory_identifier = get_last_node_identifier();
}
//SOME OTHER SHIT
int encryptionOperation(int text, int encryptedText)
{
//CHANGE THE '-' (MINUS) OPERATOR TO SOMETHING YOU WANT TO USE I GUESS
return text - encryptedText;
//I DO NOT RECOMMEND CHANGING THIS, BUT IF YOU WANT TO, XOR IS A GOOD OPERATOR (IDK IF OTHERS WORK lmao)
}

View File

@ -1,123 +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 <why2.h>
int encryptionOperationTest(int text, int encryptedText)
{
return text ^ encryptedText;
}
int main(void)
{
//VARIABLES
char *textBuffer;
char *keyBuffer;
char *statusBuffer;
char *outputBuffer = why2_malloc(1); //THIS IS TEMP ALLOCATION
int exit_code = 0;
unsigned long timeBuffer;
FILE *outputStreamBuffer = stdout;
//FLAGS
why2_input_flags flags =
{
0, //SKIP CHECK
0, //NO OUTPUT
0, //UPDATE
WHY2_v3, //LATEST VERSION
WHY2_OUTPUT_TEXT //READABLE TEXT OUTPUT
};
//SET FLAGS
why2_set_flags(flags);
//SET KEY_LENGTH TO 100
why2_set_key_length(100);
//SET ENCRYPTION_SEPARATOR TO '|'
why2_set_encryption_separator('\'');
//SET outputBuffer to NULL
outputBuffer[0] = '\0';
//SET encryptionOperation to encryptionOperationTest
why2_set_encryption_operation(encryptionOperationTest);
//ENCRYPT
why2_output_flags encrypted = why2_encrypt_text(WHY2_TEST_TEXT, NULL);
textBuffer = why2_strdup(encrypted.output_text); //GET ENCRYPTED TEXT
keyBuffer = why2_strdup(encrypted.used_key); //GET KEY
timeBuffer = encrypted.elapsed_time; //GET TIME 1
//DEALLOCATE BUFFER
why2_deallocate_output(encrypted);
//DECRYPT
encrypted = why2_decrypt_text(textBuffer, keyBuffer);
timeBuffer += encrypted.elapsed_time; //GET TIME 1
//COMPARE DIFFERENCE
if (strcmp(encrypted.output_text, WHY2_TEST_TEXT) == 0 && encrypted.exit_code == 0) //WHY2_SUCCESS
{
statusBuffer = why2_strdup("successful");
}
else //FAILURE
{
statusBuffer = why2_strdup("failed");
outputBuffer = why2_realloc(outputBuffer, strlen(encrypted.output_text) + 6);
sprintf(outputBuffer, "\t\t\"%s\"\n", encrypted.output_text);
outputStreamBuffer = stderr;
exit_code = 1;
}
//PRINT OUTPUT
fprintf
(
outputStreamBuffer,
"Test %s!\n\n"
"TEXT: \t\t\"%s\"\n%s"
"OUTPUT: \t\"%s\"\n"
"KEY: \t\t\"%s\"\n"
"TIME: \t\t\"%lums\"\n"
"UNUSED KEY: \t\"%lu\"\n"
"REPEATED KEY: \t\"%lu\"\n"
"EXIT CODE: \t\"%d\"\n"
, statusBuffer, WHY2_TEST_TEXT, outputBuffer, textBuffer, encrypted.used_key, timeBuffer / 1000, encrypted.unused_key_size, encrypted.repeated_key_size, encrypted.exit_code
);
//DEALLOCATION
why2_deallocate(textBuffer);
why2_deallocate(keyBuffer);
why2_deallocate(statusBuffer);
why2_deallocate(outputBuffer);
why2_deallocate_output(encrypted);
return exit_code;
}

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,248 +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/>.
*/
/*
bro this whole file is fucked up af...
...or maybe I am...
*/
#include <why2/memory.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <why2/flags.h>
//LOCAL
enum POINTER_TYPES
{
ALLOCATION,
FOPEN,
OPENDIR
};
typedef struct node
{
void *pointer;
char *identifier;
enum POINTER_TYPES type;
struct node *next;
} node_t; //SINGLE LINKED LIST
node_t *head = NULL;
void push_to_list(void *pointer, enum POINTER_TYPES type)
{
//CREATE NODE
node_t *new_node = malloc(sizeof(node_t));
node_t *buffer = head;
new_node -> pointer = pointer;
new_node -> identifier = why2_get_memory_identifier();
new_node -> type = type;
new_node -> next = NULL;
if (head == NULL) //INIT LIST
{
head = new_node;
} else
{
while (buffer -> next != NULL) buffer = buffer -> next; //GET TO THE END OF LIST
buffer -> next = new_node; //LINK
}
}
void remove_node(node_t *node)
{
if (node == NULL) return; //NULL NODE
node_t *buffer_1 = head;
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;
}
//DEALLOCATION
free(node);
}
node_t *get_node(void *pointer)
{
if (head == NULL || pointer == NULL) return NULL; //EMPTY LIST
node_t *buffer = head;
while (buffer -> next != NULL)
{
if (buffer -> pointer == pointer) return buffer;
buffer = buffer -> next;
}
if (pointer != buffer -> pointer) buffer = NULL; //PREVENT FROM RETURNING INVALID NODE
return buffer;
}
//GLOBAL
void *why2_malloc(unsigned long size)
{
void *allocated = malloc(size);
push_to_list(allocated, ALLOCATION);
return allocated;
}
void *why2_calloc(unsigned long element, unsigned long size)
{
void *allocated = calloc(element, size);
push_to_list(allocated, ALLOCATION);
return allocated;
}
void *why2_realloc(void *pointer, unsigned long size)
{
if (pointer != NULL) why2_deallocate(pointer);
void *allocated = malloc(size);
push_to_list(allocated, ALLOCATION);
return allocated;
}
char *why2_strdup(char *string)
{
char *allocated = strdup(string);
push_to_list(allocated, ALLOCATION);
return allocated;
}
void *why2_fopen(char *name, char *modes)
{
void *opened = fopen(name, modes);
push_to_list(opened, FOPEN);
return opened;
}
void *why2_fdopen(int file, char *modes)
{
void *opened = fdopen(file, modes);
push_to_list(opened, FOPEN);
return opened;
}
void *why2_opendir(char *name)
{
void *opened = opendir(name);
push_to_list(opened, OPENDIR);
return opened;
}
void why2_deallocate(void *pointer)
{
if (pointer == NULL) return; //DEALLOCATING NULL
//VARIABLES
node_t *node = get_node(pointer);
if (node == NULL) return;
switch (node -> type) //DEALLOCATE BY THE CORRECT WAY
{
case ALLOCATION: //STANDARD MALLOC, CALLOC OR REALLOC
free(pointer);
break;
case FOPEN: //FOPEN OR FDOPEN
fclose(pointer);
break;
case OPENDIR: //OPENDIR SYSTEM CALL
closedir(pointer);
break;
}
remove_node(node); //REMOVE FROM LIST IF FOUND
}
void why2_clean_memory(char *identifier)
{
if (head == NULL) return; //LIST IS EMPTY
node_t *buffer = head;
void *pointer_buffer = NULL;
why2_bool force_deallocating = identifier == why2_get_default_memory_identifier();
while (buffer -> next != NULL) //GO TROUGH LIST
{
if (buffer -> identifier == identifier || force_deallocating) pointer_buffer = buffer -> pointer;
buffer = buffer -> next;
if (pointer_buffer != NULL)
{
why2_deallocate(pointer_buffer);
pointer_buffer = NULL;
}
}
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_bool why2_allocated(void *pointer)
{
return get_node(pointer) != NULL;
}

View File

@ -1,493 +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/>.
*/
#define _XOPEN_SOURCE 500
#include <why2/misc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/random.h>
#include <ftw.h>
#include <curl/curl.h>
#include <json-c/json.h>
#include <git2.h>
#include <why2/flags.h>
#include <why2/memory.h>
int multiply_cb(int a, int b) { return a * b; }
int subtract_cb(int a, int b) { return a - b; }
int 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 rv = remove(fpath);
if (rv) perror(fpath);
return rv;
}
int removeDirectory(char *path)
{
return nftw(path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
}
void why2_directory(void)
{
struct stat st;
char *buffer = why2_replace(WHY2_CONFIG_DIR, "{USER}", getenv("USER"));
//CREATE USER CONFIG FOLDER
if (stat(buffer, &st) == -1)
{
mkdir(buffer, 0700);
}
//DEALLOCATION
why2_deallocate(buffer);
}
enum WHY2_EXIT_CODES why2_check_version(void)
{
if (why2_get_flags().no_check) return WHY2_SUCCESS;
why2_set_memory_identifier("core_version_check");
why2_directory(); //MAKE SURE WHY2 DIR EXISTS
//FILE-CHECK VARIABLES
int not_found_buffer = 0;
//GET VERSION FILE
char *version_file = why2_replace(WHY2_VERSIONS_NAME, "{USER}", getenv("USER"));
//CURL VARIABLES
CURL *curl = curl_easy_init();
FILE *file_buffer = why2_fopen(version_file, "w+");
//GET versions.json
curl_easy_setopt(curl, CURLOPT_URL, WHY2_VERSIONS_URL);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, file_buffer);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, WHY2_CURL_TIMEOUT);
//DOWNLOAD versions.json
curl_easy_perform(curl);
//CLEANUP
curl_easy_cleanup(curl);
why2_deallocate(file_buffer);
while (access(version_file, R_OK) != 0)
{
not_found_buffer++;
if (not_found_buffer == WHY2_NOT_FOUND_TRIES)
{
if (!why2_get_flags().no_output) fprintf(stderr, "%s'%s' not found! Exiting...\n", WHY2_CLEAR_SCREEN, version_file);
why2_clean_memory("core_version_check");
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);
sleep(1);
}
//JSON VARIABLES
char *buffer;
long buffer_size;
struct json_object *parsed_json;
struct json_object *active;
//COUNT LENGTH OF buffer AND STORE IT IN bufferSize
file_buffer = why2_fopen(version_file, "r");
fseek(file_buffer, 0, SEEK_END);
buffer_size = ftell(file_buffer);
rewind(file_buffer); //REWIND file_buffer (NO SHIT)
//SET LENGTH OF buffer
buffer = why2_calloc(buffer_size + 1, sizeof(char));
//LOAD jsonFile
if (fread(buffer, buffer_size, 1, file_buffer) != 1)
{
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");
// return WHY2_DOWNLOAD_FAILED;
}
buffer[buffer_size] = '\0';
//CHECK FOR TEXT IN buffer
if (strcmp(buffer, "") == 0)
{
if (!why2_get_flags().no_output) fprintf(stderr, "You probably aren't connected to internet! This release could be unsafe!\n\n");
//WAIT FOR 5 SECONDS
sleep(5);
why2_clean_memory("core_version_check");
return WHY2_SUCCESS;
}
//CLEANUP
why2_deallocate(file_buffer);
//GET
parsed_json = 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);
if (strcmp(WHY2_VERSION, json_object_get_string(active)) != 0)
{
//UPDATE
if (why2_get_flags().update)
{
//CHECK FOR ROOT PERMISSIONS
if (getuid() != 0)
{
if (!why2_get_flags().no_output) fprintf(stderr, "You need to be root to update!\t[I DO NOT RECOMMEND USING THIS]\n");
why2_clean_memory("core_version_check");
return WHY2_WHY2_UPDATE_FAILED;
}
//VARIABLES
git_repository *repo = NULL;
int exit_code;
char *install_command;
int install_code;
//MESSAGE
if (!why2_get_flags().no_output) printf("Your WHY2 version is outdated!\nUpdating...\t[BETA]\n\n");
//CHECK IF WHY2 REPO ISN'T ALREADY FOUND IN 'WHY2_UPDATE_NAME'
if (access(WHY2_UPDATE_NAME, F_OK) == 0)
{
removeDirectory(WHY2_UPDATE_NAME);
}
git_libgit2_init(); //START GIT2
exit_code = git_clone(&repo, WHY2_UPDATE_URL, WHY2_UPDATE_NAME, NULL); //CLONE
git_libgit2_shutdown(); //STOP GIT2
//CHECK FOR ERRORS
if (exit_code != 0)
{
if (!why2_get_flags().no_output) fprintf(stderr, "Updating failed! (cloning)\n");
why2_clean_memory("core_version_check");
return WHY2_WHY2_UPDATE_FAILED;
}
//COUNT install_command LENGTH & ALLOCATE IT
install_command = why2_replace(WHY2_UPDATE_COMMAND, "{DIR}", WHY2_UPDATE_NAME);
install_code = system(install_command); //INSTALL
//REMOVE versions.json - OTHERWISE WILL CAUSE SEGFAULT IN NEXT RUN
remove(version_file);
why2_deallocate(install_command);
//CHECK FOR ERRORS
if (install_code != 0)
{
if (!why2_get_flags().no_output) fprintf(stderr, "Updating failed! (installing)\n");
why2_clean_memory("core_version_check");
return WHY2_WHY2_UPDATE_FAILED;
}
} else
{
//COUNT WHY2_VERSIONS BEHIND
int versions_index = -1;
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
if (strcmp(json_object_get_string(json_object_array_get_idx(deprecated, i)), WHY2_VERSION) == 0)
{
versions_index = i;
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);
}
}
}
//DEALLOCATION
json_object_put(parsed_json); //THIS FREES EVERY json_object - AT LEAST JSON-C'S DOCUMENTATION SAYS THAT
why2_deallocate(buffer);
why2_deallocate(version_file);
why2_reset_memory_identifier();
return WHY2_SUCCESS;
}
void why2_generate_text_key_chain(char *key, int *text_key_chain, int text_key_chain_size)
{
int number_buffer;
int number_buffer_2 = 0;
int number_buffer_3 = 0;
int (*cb)(int, int);
for (int i = 0; i < text_key_chain_size; i++)
{
number_buffer = i;
//CHECK, IF number_buffer ISN'T GREATER THAN keyLength AND CUT WHY2_UNUSED LENGTH
while (number_buffer >= (int) why2_get_key_length())
{
number_buffer -= why2_get_key_length();
}
//SET tkch VERSION
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
if ((number_buffer + 1) % 3 == 0)
{
cb = multiply_cb;
}
else if ((number_buffer + 1) % 2 == 0)
{
cb = subtract_cb;
}
else
{
cb = sum_cb;
}
text_key_chain[number_buffer_2] = cb(key[number_buffer], key[number_buffer_3]);
}
}
void why2_deallocate_output(why2_output_flags flags)
{
why2_deallocate(flags.output_text);
why2_deallocate(flags.used_key);
flags.elapsed_time = 0;
flags.exit_code = WHY2_SUCCESS;
flags.repeated_key_size = 0;
flags.unused_key_size = 0;
flags.output_text = NULL;
flags.used_key = NULL;
}
enum WHY2_EXIT_CODES why2_check_key(char *key)
{
if (strlen(key) < why2_get_key_length())
{
if (!why2_get_flags().no_output) fprintf(stderr, "Key must be at least %lu characters long!\n", why2_get_key_length());
return WHY2_INVALID_KEY;
}
return WHY2_SUCCESS;
}
enum WHY2_EXIT_CODES why2_check_text(char *text)
{
if (strcmp(text, "") == 0)
{
if (!why2_get_flags().no_output) fprintf(stderr, "No text to encrypt!\n");
return WHY2_INVALID_TEXT;
}
return WHY2_SUCCESS;
}
unsigned long why2_count_int_length(int number)
{
int returning = 1;
int buffer = 10;
//CHECK FOR NEGATIVE NUMBER
if (number < 0)
{
returning++;
number *= -1;
}
//COUNT LENGTH
while (buffer <= number)
{
buffer *= 10;
returning++;
}
return returning;
}
unsigned long why2_count_unused_key_size(char *text, char *key)
{
unsigned long returning = 0;
if ((long double) (strlen(key)) / 2 > strlen(text))
{
returning = strlen(key) - 2 * strlen(text);
}
return returning;
}
unsigned long why2_count_repeated_key_size(char *text, char *key)
{
unsigned long returning = 0;
if (strlen(key) < 2 * strlen(text))
{
returning = 2 * strlen(text) - strlen(key);
}
return returning;
}
unsigned long why2_compare_time_micro(struct timeval startTime, struct timeval finishTime)
{
return (finishTime.tv_sec - startTime.tv_sec) * 1000000 + finishTime.tv_usec - startTime.tv_usec;
}
char *why2_generate_key(int key_length)
{
int number_buffer;
unsigned int random_buffer;
char *key;
key = why2_malloc(key_length + 1);
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
number_buffer = (random_buffer % 52) + 1;
//GET CHAR FROM numberBuffer
if (number_buffer > 26)
{
number_buffer += 70;
} else
{
number_buffer += 64;
}
key[i] = (char) number_buffer;
}
key[key_length] = '\0';
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
}

147
src/lib/decrypter.c Normal file
View File

@ -0,0 +1,147 @@
#include <why2/decrypter.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
#include <why2/flags.h>
#include <why2/misc.h>
outputFlags decryptText(char *text, char *keyNew)
{
//CHECK VARIABLE
int checkExitCode;
//TIME VARIABLES
struct timeval startTime;
struct timeval finishTime;
gettimeofday(&startTime, NULL);
//CHECK FOR ACTIVE VERSION
if ((checkExitCode = checkVersion()) != SUCCESS)
{
return noOutput(checkExitCode);
}
//CHECK FOR INVALID text
if ((checkExitCode = checkText(text)) != SUCCESS)
{
return noOutput(checkExitCode);
}
//CHECK FOR INVALID key
if ((checkExitCode = checkKey(keyNew)) != SUCCESS)
{
return noOutput(checkExitCode);
}
//REDEFINE keyLength
setKeyLength(strlen(keyNew));
//VARIABLES
char *returningText;
int numberBuffer = 1;
char *textBuffer;
int textKeyChainLength;
int *textKeyChain;
char *key = malloc(strlen(keyNew) + 1);
int *encryptedTextKeyChain;
//COPY keyNew TO key
strcpy(key, keyNew);
//GET LENGTH OF returningText AND textKeyChain
for (int i = 0; i < (int) strlen(text); i++)
{
if (text[i] == getEncryptionSeparator()) numberBuffer++;
}
//SET LENGTH (numberBuffer)
returningText = malloc(numberBuffer + 1);
textKeyChain = malloc(sizeof(int) * numberBuffer);
encryptedTextKeyChain = malloc(sizeof(int) * numberBuffer);
textKeyChainLength = numberBuffer;
//LOAD textKeyChain
generateTextKeyChain(key, textKeyChain, numberBuffer);
//LOAD encryptedTextKeyChain
for (int i = 0; i < textKeyChainLength; i++)
{
numberBuffer = 0;
//GET LENGTH OF EACH CHARACTER
for (int j = 0; j < (int) strlen(text); j++)
{
if (text[j] == getEncryptionSeparator()) break;
numberBuffer++;
}
if (i != 0)
{
textBuffer = realloc(textBuffer, numberBuffer + 1);
} else
{
textBuffer = malloc(numberBuffer + 1);
}
//CLEAN (POSSIBLY EXISTING) JUNK in textBuffer
for (int i = 0; i <= numberBuffer; i++)
{
textBuffer[i] = '\0';
}
//LOAD textBuffer
for (int j = 0; j < (int) strlen(text); j++)
{
textBuffer[j] = text[j];
if (numberBuffer == j) break;
}
encryptedTextKeyChain[i] = atoi(textBuffer);
text += numberBuffer + 1;
}
//DECRYPT TEXT
for (int i = 0; i < textKeyChainLength; i++)
{
textKeyChain[i] ^= encryptedTextKeyChain[i];
}
//FIX (CLEAN) returningText
for (int i = 0; i <= textKeyChainLength; i++)
{
returningText[i] = '\0';
}
//LOAD returningText
for (int i = 0; i < textKeyChainLength; i++)
{
returningText[i] = textKeyChain[i];
}
//GET FINISH TIME
gettimeofday(&finishTime, NULL);
//LOAD output
outputFlags output =
{
returningText, //DECRYPTED TEXT
key, //USED KEY
countUnusedKeySize(returningText, key), // NUMBER OF UNUSED CHARS IN KEY
countRepeatedKeySize(returningText, key), //NUMBER OF REPEATED CHARS IN KEY
compareTimeMicro(startTime, finishTime), // ELAPSED TIME
SUCCESS //EXIT CODE
};
//DEALLOCATION
free(textKeyChain);
free(encryptedTextKeyChain);
free(textBuffer);
return output;
}

153
src/lib/encrypter.c Normal file
View File

@ -0,0 +1,153 @@
#include <why2/encrypter.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>
#include <why2/flags.h>
#include <why2/misc.h>
outputFlags encryptText(char *text, char *keyNew)
{
//CHECK VARIABLE
int checkExitCode;
//TIME VARIABLES
struct timeval startTime;
struct timeval finishTime;
gettimeofday(&startTime, NULL);
//CHECK FOR ACTIVE VERSION
if ((checkExitCode = checkVersion()) != SUCCESS)
{
return noOutput(checkExitCode);
}
//CHECK FOR INVALID text
if ((checkExitCode = checkText(text)) != SUCCESS)
{
return noOutput(checkExitCode);
}
//VARIABLES
char *key = malloc(getKeyLength() + 1);
char *returningText;
char *textBuffer;
int *textKeyChain = malloc(sizeof(int) * strlen(text));
int numberBuffer;
FILE *fileBuffer;
//TRY TO MAKE RANDOM GENERATION REALLY "RANDOM"
fileBuffer = fopen("/dev/urandom", "r");
fread(&numberBuffer, 4, 1, fileBuffer);
srand(numberBuffer);
if (numberBuffer < 0) numberBuffer *= -1; //MAKE numberBuffer POSITIVE
if (keyNew != NULL)
{
//CHECK FOR INVALID key
if ((checkExitCode = checkKey(keyNew)) != SUCCESS)
{
return noOutput(checkExitCode);
}
strcpy(key, keyNew);
//REDEFINE keyLength
setKeyLength(strlen(key));
goto skipKey;
}
//LOAD KEY
for (int i = 0; i < (int) getKeyLength(); i++)
{
//SET numberBuffer TO RANDOM NUMBER BETWEEN 0 AND 52
numberBuffer = (rand() % 52) + 1;
//GET CHAR FROM numberBuffer
if (numberBuffer > 26)
{
numberBuffer += 70;
}
else
{
numberBuffer += 64;
}
key[i] = (char) numberBuffer;
}
key[getKeyLength()] = '\0';
skipKey:
//LOAD textKeyChain
generateTextKeyChain(key, textKeyChain, strlen(text));
//ACTUALLY ENCRYPT TEXT
for (int i = 0; i < (int) strlen(text); i++)
{
textKeyChain[i] ^= (int) text[i];
}
//COUNT REQUIRED SIZE FOR returningText
for (int i = 0; i < (int) strlen(text); i++)
{
numberBuffer += countIntLength(textKeyChain[i]);
}
//ALLOCATE returningText (WITH THE SEPARATORS)
returningText = malloc(numberBuffer + strlen(text) - 1);
strcpy(returningText, "");
//LOAD returningText
for (int i = 0; i < (int) strlen(text); i++)
{
numberBuffer = sizeof(int) * countIntLength(textKeyChain[i]);
if (i != 0)
{
textBuffer = realloc(textBuffer, numberBuffer);
}
else
{
textBuffer = malloc(numberBuffer);
}
sprintf(textBuffer, "%d", textKeyChain[i]);
strcat(returningText, textBuffer);
if (i != (int) strlen(text) - 1)
{
textBuffer = realloc(textBuffer, 2);
sprintf(textBuffer, "%c", getEncryptionSeparator());
strcat(returningText, textBuffer);
}
}
//GET FINISH TIME
gettimeofday(&finishTime, NULL);
//LOAD output
outputFlags output =
{
returningText, //ENCRYPTED TEXT
key, //GENERATED/USED KEY
countUnusedKeySize(text, key), // NUMBER OF UNUSED CHARS IN KEY
countRepeatedKeySize(text, key), //NUMBER OF REPEATED CHARS IN KEY
compareTimeMicro(startTime, finishTime), // ELAPSED TIME
SUCCESS //EXIT CODE
};
//DEALLOCATION
free(textKeyChain);
free(textBuffer);
fclose(fileBuffer);
return output;
}

67
src/lib/flags.c Normal file
View File

@ -0,0 +1,67 @@
#include <why2/flags.h>
#include <stdlib.h>
//CONSTS (this is just local)
#define DEFAULT_FLAGS (inputFlags) { 0, 0, 0 }
//VARIABLES
char encryptionSeparator = '.'; //NOPE > DO NOT TOUCH THIS, USE setEncryptionSeparator instead <
unsigned long keyLength = 50; //LENGTH OF KEY > DO NOT TOUCH THIS, USE setKeyLength instead <
inputFlags flags = DEFAULT_FLAGS;
//GETTERS
char getEncryptionSeparator()
{
return encryptionSeparator;
}
unsigned long getKeyLength()
{
return keyLength;
}
inputFlags defaultFlags()
{
return DEFAULT_FLAGS;
}
inputFlags getFlags()
{
return flags;
}
outputFlags noOutput(_Bool exitCode)
{
char *emptyText = malloc(1); //TEXT
emptyText[0] = '\0';
char *emptyKey = malloc(getKeyLength() + 1); //KEY
for (int i = 0; i < (int) getKeyLength(); i++)
{
emptyKey[i] = 'x';
}
emptyKey[getKeyLength()] = '\0';
return (outputFlags) { emptyText, emptyKey, 0, 0, 0, exitCode };
}
//SETTERS
void setEncryptionSeparator(char encryptionSeparatorNew)
{
if (encryptionSeparatorNew <= 31) return;
encryptionSeparator = encryptionSeparatorNew;
}
void setKeyLength(int keyLengthNew)
{
if (keyLengthNew < 1) return;
keyLength = keyLengthNew;
}
void setFlags(inputFlags newFlags)
{
flags = newFlags;
}

374
src/lib/misc.c Normal file
View File

@ -0,0 +1,374 @@
#define _XOPEN_SOURCE 500
#include <why2/misc.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include <ftw.h>
#include <curl/curl.h>
#include <json-c/json.h>
#include <git2.h>
#include <why2/flags.h>
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; }
double doMathematicalOperation(int a, int b, double (*op)(int, int))
{
return op(a, b);
}
int unlink_cb(const char *fpath, UNUSED const struct stat *sb, UNUSED int typeflag, UNUSED struct FTW *ftwbuf)
{
int rv = remove(fpath);
if (rv) perror(fpath);
return rv;
}
int removeDirectory(char *path)
{
return nftw(path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
}
char *replaceWord(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*) 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;
}
_Bool checkVersion()
{
if (getFlags().noCheck) return SUCCESS;
//FILE-CHECK VARIABLES
int notFoundBuffer = 0;
//CURL VARIABLES
CURL *curl = curl_easy_init();
FILE *fileBuffer = fopen(VERSIONS_NAME, "w+");
//GET versions.json
curl_easy_setopt(curl, CURLOPT_URL, VERSIONS_URL);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fileBuffer);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, CURL_TIMEOUT);
//DOWNLOAD versions.json
curl_easy_perform(curl);
//CLEANUP
curl_easy_cleanup(curl);
fclose(fileBuffer);
while (access(VERSIONS_NAME, R_OK) != 0)
{
notFoundBuffer++;
if (notFoundBuffer == NOT_FOUND_TRIES)
{
if (!getFlags().noOutput) fprintf(stderr, "%s'%s' not found! Exiting...\n", CLEAR_SCREEN, VERSIONS_NAME);
return DOWNLOAD_FAILED;
}
if (!getFlags().noOutput) printf("%s'%s' not found (%dx)! Trying again in a second.\n", CLEAR_SCREEN, VERSIONS_NAME, notFoundBuffer);
sleep(1);
}
//JSON VARIABLES
char *buffer;
struct json_object *parsedJson;
struct json_object *active;
int bufferSize;
//COUNT LENGTH OF buffer AND STORE IT IN bufferSize
fileBuffer = fopen(VERSIONS_NAME, "r");
fseek(fileBuffer, 0, SEEK_END);
bufferSize = ftell(fileBuffer);
rewind(fileBuffer); //REWIND fileBuffer (NO SHIT)
//SET LENGTH OF buffer
buffer = malloc(bufferSize + 1);
//FIX buffer
strcpy(buffer, "");
//LOAD jsonFile
fread(buffer, bufferSize, 1, fileBuffer);
//CHECK FOR TEXT IN buffer
if (strcmp(buffer, "") == 0)
{
if (!getFlags().noOutput) fprintf(stderr, "You probably aren't connected to internet! This release could be unsafe!\n\n");
//WAIT FOR 5 SECONDS
sleep(5);
free(buffer);
fclose(fileBuffer);
return SUCCESS;
}
//CLEANUP
fclose(fileBuffer);
//GET
parsedJson = json_tokener_parse(buffer);
json_object_object_get_ex(parsedJson, "active", &active);
if (strcmp(VERSION, json_object_get_string(active)) != 0)
{
//UPDATE
if (getFlags().update)
{
//CHECK FOR ROOT PERMISSIONS
if (getuid() != 0)
{
if (!getFlags().noOutput) fprintf(stderr, "You need to be root to update!\t[I DO NOT RECOMMEND USING THIS]\n");
return UPDATE_FAILED;
}
//VARIABLES
git_repository *repo = NULL;
int exitCode;
char *installCommand;
int installCode;
//MESSAGE
if (!getFlags().noOutput) printf("Your WHY2 version is outdated!\nUpdating...\t[BETA]\n\n");
//CHECK IF WHY2 REPO ISN'T ALREADY FOUND IN 'UPDATE_NAME'
if (access(UPDATE_NAME, F_OK) == 0)
{
removeDirectory(UPDATE_NAME);
}
git_libgit2_init(); //START GIT2
exitCode = git_clone(&repo, UPDATE_URL, UPDATE_NAME, NULL); //CLONE
git_libgit2_shutdown(); //STOP GIT2
//CHECK FOR ERRORS
if (exitCode != 0)
{
if (!getFlags().noOutput) fprintf(stderr, "Updating failed! (cloning)\n");
return UPDATE_FAILED;
}
//COUNT installCommand LENGTH & ALLOCATE IT
installCommand = replaceWord(UPDATE_COMMAND, "{DIR}", UPDATE_NAME);
installCode = system(installCommand); //INSTALL
//REMOVE versions.json - OTHERWISE WILL CAUSE SEGFAULT IN NEXT RUN
remove(VERSIONS_NAME);
free(installCommand);
//CHECK FOR ERRORS
if (installCode != 0)
{
if (!getFlags().noOutput) fprintf(stderr, "Updating failed! (installing)\n");
return UPDATE_FAILED;
}
goto deallocation; //GREAT SUCCESS!
}
//COUNT 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++)
{
//IT'S A MATCH, BABY :D
if (strcmp(json_object_get_string(json_object_array_get_idx(deprecated, i)), VERSION) == 0)
{
versionsIndex = i;
break;
}
}
//versions.json DOESN'T CONTAIN VERSION (THIS WILL NOT HAPPEN IF YOU WILL NOT EDIT IT)
if (versionsIndex == -1)
{
if (!getFlags().noOutput) printf("Version %s not found! Check your flags.\n\n", VERSION);
free(deprecated);
goto deallocation;
}
//COUNT versionsBuffer
versionsBuffer = json_object_array_length(deprecated) - versionsIndex;
if (!getFlags().noOutput) fprintf(stderr, "This release could be unsafe! You're %d versions behind! (%s/%s)\n\n", versionsBuffer, VERSION, json_object_get_string(active));
//WAIT FOR 5 SECONDS
free(deprecated);
sleep(5);
}
deallocation:
//DEALLOCATION
free(parsedJson);
free(active);
free(buffer);
return SUCCESS;
}
void generateTextKeyChain(char *key, int *textKeyChain, int textKeyChainSize)
{
int numberBuffer;
int numberBuffer2;
double (*cb)(int, int);
for (int i = 0; i < textKeyChainSize; i++)
{
numberBuffer = i;
//CHECK, IF numberBuffer ISN'T GREATER THAN keyLength AND CUT UNUSED LENGTH
while (numberBuffer >= (int) getKeyLength())
{
numberBuffer -= getKeyLength();
}
numberBuffer2 = getKeyLength() - (numberBuffer + (i < textKeyChainSize));
//FILL textKeyChain
if ((numberBuffer + 1) % 3 == 0)
{
cb = multiply_cb;
}
else if ((numberBuffer + 1) % 2 == 0)
{
cb = subtract_cb;
}
else
{
cb = sum_cb;
}
textKeyChain[textKeyChainSize - (i + 1)] = doMathematicalOperation(key[numberBuffer], key[numberBuffer2], cb);
}
}
void deallocateOutput(outputFlags flags)
{
free(flags.outputText);
free(flags.usedKey);
}
_Bool checkKey(char *key)
{
if (strlen(key) < getKeyLength())
{
if (!getFlags().noOutput) fprintf(stderr, "Key must be at least %lu characters long!\n", getKeyLength());
return INVALID_KEY;
}
return SUCCESS;
}
_Bool checkText(char *text)
{
if (strcmp(text, "") == 0)
{
if (!getFlags().noOutput) fprintf(stderr, "No text to encrypt!\n");
return INVALID_TEXT;
}
return SUCCESS;
}
unsigned long countIntLength(int number)
{
int returning = 1;
int buffer = 10;
//CHECK FOR NEGATIVE NUMBER
if (number < 0)
{
returning++;
number *= -1;
}
//COUNT LENGTH
while (buffer <= number)
{
buffer *= 10;
returning++;
}
return returning;
}
unsigned long countUnusedKeySize(char *text, char *key)
{
unsigned long returning = 0;
if ((long double) (strlen(key)) / 2 > strlen(text))
{
returning = strlen(key) - 2 * strlen(text);
}
return returning;
}
unsigned long countRepeatedKeySize(char *text, char *key)
{
unsigned long returning = 0;
if (strlen(key) < 2 * strlen(text))
{
returning = 2 * strlen(text) - strlen(key);
}
return returning;
}
unsigned long compareTimeMicro(struct timeval startTime, struct timeval finishTime)
{
return (finishTime.tv_sec - startTime.tv_sec) * 1000000 + finishTime.tv_usec - startTime.tv_usec;
}

98
src/lib/test/main.c Normal file
View File

@ -0,0 +1,98 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <why2.h>
int main(void)
{
//VARIABLES
char *textBuffer = malloc(256);
char *keyBuffer;
char *statusBuffer;
char *outputBuffer = malloc(1); //THIS IS TEMP ALLOCATION
int exitCode = 0;
unsigned long timeBuffer;
FILE *outputStreamBuffer = stdout;
//FLAGS
inputFlags flags =
{
0, //SKIP CHECK
0, //NO OUTPUT
0 //UPDATE
};
//SET FLAGS
setFlags(flags);
//SET KEY_LENGTH TO 100
setKeyLength(100);
keyBuffer = malloc(getKeyLength() + 1);
//SET ENCRYPTION_SEPARATOR TO '|'
setEncryptionSeparator('|');
//SET outputBuffer to NULL
outputBuffer[0] = '\0';
//ENCRYPT
outputFlags encrypted = encryptText(TEST_TEXT, NULL);
strcpy(textBuffer, encrypted.outputText); //GET ENCRYPTED TEXT
strcpy(keyBuffer, encrypted.usedKey); //GET KEY
timeBuffer = encrypted.elapsedTime; //GET TIME 1
//DEALLOCATE BUFFER
deallocateOutput(encrypted);
//DECRYPT
encrypted = decryptText(textBuffer, keyBuffer);
timeBuffer += encrypted.elapsedTime; //GET TIME 1
//COMPARE DIFFERENCE
if (strcmp(encrypted.outputText, TEST_TEXT) == 0 && encrypted.exitCode == 0) //SUCCESS
{
statusBuffer = malloc(11);
strcpy(statusBuffer, "successful");
}
else //FAILURE
{
statusBuffer = malloc(8);
strcpy(statusBuffer, "failed");
outputBuffer = realloc(outputBuffer, strlen(encrypted.outputText) + 6);
sprintf(outputBuffer, "\t\t\"%s\"\n", encrypted.outputText);
outputStreamBuffer = stderr;
exitCode = 1;
}
//PRINT OUTPUT
fprintf
(
outputStreamBuffer,
"Test %s!\n\n"
"TEXT: \t\t\"%s\"\n%s"
"OUTPUT: \t\"%s\"\n"
"KEY: \t\t\"%s\"\n"
"TIME: \t\t\"%lums\"\n"
"UNUSED KEY: \t\"%lu\"\n"
"REPEATED KEY: \t\"%lu\"\n"
"EXIT CODE: \t\"%d\"\n"
, statusBuffer, TEST_TEXT, outputBuffer, textBuffer, encrypted.usedKey, timeBuffer / 1000, encrypted.unusedKeySize, encrypted.repeatedKeySize, encrypted.exitCode
);
//DEALLOCATION
free(textBuffer);
free(keyBuffer);
free(statusBuffer);
free(outputBuffer);
deallocateOutput(encrypted);
return exitCode;
}

View File

@ -1,52 +0,0 @@
#include <stdio.h>
#include <string.h>
#include <why2.h>
int main(void)
{
why2_log_file log_file = why2_init_logger(WHY2_TEST_DIRECTORY); //INIT LOGGER
char *key = why2_generate_key(strlen(WHY2_LOGGER_TEST_TEXT) * 2);
//SET FLAGS
why2_set_flags
(
(why2_input_flags)
{
1,
1,
0,
WHY2_v3,
WHY2_OUTPUT_TEXT
}
);
why2_set_log_flags
(
(why2_log_flags)
{
key
}
);
why2_write_log(log_file.file, WHY2_LOGGER_TEST_TEXT); //WRITE
//PRINT
printf
(
"Hi.\n"
"This is a simple application written using WHY2's logger module.\n\n"
"Come on, open \"%s\"... I wrote something special there :)\n\n"
"Thank you so much for supporting this project!\n",
log_file.filename
);
//DEALLOCATION
why2_deallocate(key);
why2_deallocate_logger(log_file);
return 0;
}

View File

@ -1,36 +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/logger/flags.h>
#include <stdio.h>
//VARIABLES
why2_log_flags flags = { NULL };
//GETTERS
why2_log_flags why2_get_log_flags(void)
{
return flags;
}
//SETTERS
void why2_set_log_flags(why2_log_flags why2_log_flagsNew)
{
flags = why2_log_flagsNew;
}

View File

@ -1,163 +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/logger/logger.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <dirent.h>
#include <time.h>
#include <sys/stat.h>
#include <why2/logger/flags.h>
#include <why2/logger/utils.h>
#include <why2/encrypter.h>
#include <why2/memory.h>
#include <why2/misc.h>
why2_log_file why2_init_logger(char *directoryPath)
{
why2_set_memory_identifier("logger_logfile_init");
//VARIABLES
struct stat st;
struct dirent *entry;
time_t timeL = time(NULL);
struct tm tm = *localtime(&timeL);
int buffer = 1;
int file;
char *filePath = why2_malloc(strlen(directoryPath) + 1 + strlen(WHY2_LOG_FORMAT) + 1);
char *dateBuffer = why2_malloc(strlen(WHY2_LOG_FORMAT_START) + 1);
char *latestBuffer = why2_malloc(strlen(directoryPath) + strlen(WHY2_LOG_LATEST) + 2);
char *latestFilePath = NULL;
DIR *dir;
sprintf(dateBuffer, WHY2_LOG_FORMATTING_START, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday);
//CREATE directoryPath DIRECTORY IF IT DOESN'T EXISTS ALREADY
if (stat(directoryPath, &st) == -1)
{
mkdir(directoryPath, 0700);
}
//COUNT HOW MANY LOGS WERE GENERATED THIS DAY
dir = why2_opendir(directoryPath);
while ((entry = readdir(dir)) != NULL)
{
if (entry -> d_type == DT_REG)
{
if (strncmp(dateBuffer, entry -> d_name, strlen(dateBuffer)) == 0) buffer++;
}
}
if (buffer > WHY2_MAX_USAGE) //WHY2_MAX_USAGE WAS REACHED
{
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
//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
why2_deallocate(dateBuffer);
why2_deallocate(latestBuffer);
why2_deallocate(latestFilePath);
why2_deallocate(dir);
why2_reset_memory_identifier();
return (why2_log_file)
{
file,
filePath
};
}
void why2_write_log(int loggerFile, char *logMessage)
{
//CHECK IF loggerFile IS CREATED
if (loggerFile == INVALID_FILE)
{
return; //TODO: Add some kind of error message
}
//COPY logMessage without '\n'
char *logMessageUsed = why2_strdup(logMessage);
for (int i = 0; i < (int) strlen(logMessageUsed); i++)
{
if (logMessageUsed[i] == '\n') logMessageUsed[i] = '\0';
}
//VARIABLES
char *buffer = NULL;
char *message = NULL; //FINAL MESSAGE
time_t timeL = time(NULL);
struct tm tm = *localtime(&timeL);
why2_log_flags flags = why2_get_log_flags();
//SET ENCRYPTER FLAGS
if (!why2_get_flags_changed()) why2_set_flags((why2_input_flags) { 0, 1, 0, WHY2_v3, WHY2_OUTPUT_TEXT });
if (flags.key != NULL) //ENCRYPT TEXT IF KEY WAS CHANGED
{
why2_output_flags encrypted = why2_encrypt_text(logMessageUsed, flags.key); //ENCRYPT
message = why2_strdup(encrypted.output_text); //COPY
//DEALLOCATION
why2_deallocate_output(encrypted);
why2_deallocate(logMessageUsed); //I COULD DO THIS SMART SOMEHOW, BUT I AM TOO LAZY FOR THAT SHIT
} else //FUCK ENCRYPTION, LET'S DO IT; WHY WOULD WE EVEN USE WHY2-CORE? HUH?
{
message = logMessageUsed;
}
buffer = why2_malloc(strlen(WHY2_WRITE_FORMAT) + strlen(message) + 2); //ALLOCATE
sprintf(buffer, WHY2_WRITE_FORMATTING, tm.tm_hour, tm.tm_min, tm.tm_sec, message); //LOAD MESSAGE
if (write(loggerFile, buffer, strlen(buffer)) != (ssize_t) strlen(buffer))
{
if (!why2_get_flags().no_output) fprintf(stderr, "Writing failed!");
}
//DEALLOCATION
why2_deallocate(buffer);
why2_deallocate(message);
}

View File

@ -1,79 +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 <why2.h>
int main(void)
{
//VARIABLES
why2_log_file logger = why2_init_logger(WHY2_WRITE_DIR); //INITIALIZE LOGGER FILE
char *used_key = why2_generate_key(why2_get_key_length()); //GENERATE KEY
why2_decrypted_output decrypted;
int exit_code = 0;
//FLAGS
why2_log_flags flags =
{
used_key
};
//SET FLAGS
why2_set_log_flags(flags);
//WRITE
why2_write_log(logger.file, WHY2_WRITE_MESSAGE_1);
why2_write_log(logger.file, WHY2_WRITE_MESSAGE_2);
why2_write_log(logger.file, WHY2_WRITE_MESSAGE_3);
decrypted = why2_decrypt_logger(logger); //DECRYPT
//COMPARE OUTPUT
if //WHY2_SUCCESS //TODO: Make this smart somehow
(
strcmp(decrypted.decrypted_text[0], WHY2_WRITE_MESSAGE_1) == 0 &&
strcmp(decrypted.decrypted_text[1], WHY2_WRITE_MESSAGE_2) == 0 &&
strcmp(decrypted.decrypted_text[2], WHY2_WRITE_MESSAGE_3) == 0
)
{
printf
(
"TEST SUCCESSFUL!\n\n"
"TEXT:\t\"%s\"\n"
"\t\"%s\"\n"
"\t\"%s\"\n",
decrypted.decrypted_text[0], decrypted.decrypted_text[1], decrypted.decrypted_text[2]
);
} else //FAILED
{
fprintf(stderr, "TEST FAILED!\n");
exit_code = 1;
}
//DEALLOCATION
why2_deallocate(used_key);
why2_deallocate_logger(logger);
why2_deallocate_decrypted_output(decrypted);
return exit_code;
}

View File

@ -1,147 +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/logger/utils.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <why2/decrypter.h>
#include <why2/flags.h>
#include <why2/memory.h>
#include <why2/misc.h>
#include <why2/logger/flags.h>
void why2_deallocate_logger(why2_log_file logger)
{
close(logger.file);
why2_deallocate(logger.filename);
logger.filename = NULL;
logger.file = INVALID_FILE;
}
void why2_deallocate_decrypted_output(why2_decrypted_output output)
{
for (unsigned long i = 0; i < output.length; i++)
{
why2_deallocate(output.decrypted_text[i]);
}
output.length = 0;
why2_deallocate(output.decrypted_text);
}
why2_decrypted_output why2_decrypt_logger(why2_log_file logger)
{
why2_set_memory_identifier("logger_decryption");
FILE *file = why2_fdopen(logger.file, "r");
why2_output_flags outputBuffer;
char *rawContent;
char **content;
char **contentDecrypted;
int rawContentL;
int lines = 0;
int startingAtBuffer = 0;
int contentIndexBuffer = 0;
//COUNT LENGTH OF buffer AND STORE IT IN bufferSize
fseek(file, 0, SEEK_END);
rawContentL = ftell(file);
rewind(file); //REWIND file (NO SHIT)
//ALLOCATE rawContent
rawContent = why2_calloc(rawContentL + 1, sizeof(char)); //CALLOC WILL BE USED FOR CLEANING AFTER ALLOCATION
//LOAD rawContent
if (fread(rawContent, rawContentL, 1, file) != 1)
{
if (!why2_get_flags().no_output) fprintf(stderr, "Reading file failed!\n");
why2_clean_memory("logger_decryption");
return why2_empty_decrypted_output();
}
for (int i = 0; i < rawContentL; i++)
{
if (rawContent[i] == '\n') lines++;
}
//ALLOCATE content & contentDecrypted
content = why2_calloc(lines + 1, sizeof(char*));
contentDecrypted = why2_calloc(lines + 1, sizeof(char*));
for (int i = 0; i < rawContentL; i++) //LOAD rawContent AND SPLIT TO content
{
if (rawContent[i] == '\n') //END OF ONE LINE
{
content[contentIndexBuffer] = why2_calloc((i - (startingAtBuffer + strlen(WHY2_WRITE_FORMAT)) + 2), sizeof(char)); //ALLOCATE ELEMENT
for (int j = startingAtBuffer + strlen(WHY2_WRITE_FORMAT); j <= i; j++) //LOAD CONTENT OF EACH LINE
{
content[contentIndexBuffer][j - (startingAtBuffer + strlen(WHY2_WRITE_FORMAT))] = rawContent[j]; //SET
}
contentIndexBuffer++;
startingAtBuffer = i + 1;
}
}
for (int i = 0; i < lines; i++) //DECRYPT content
{
outputBuffer = why2_decrypt_text(content[i], why2_get_log_flags().key); //DECRYPT
contentDecrypted[i] = why2_strdup(outputBuffer.output_text); //COPY
why2_deallocate_output(outputBuffer); //DEALLOCATE outputBuffer
}
//DEALLOCATION
why2_deallocate(rawContent);
why2_deallocate(file);
why2_deallocate_decrypted_output((why2_decrypted_output) { content, lines }); //fuck the system lmao
why2_reset_memory_identifier();
return (why2_decrypted_output)
{
contentDecrypted,
lines
};
}
why2_log_file why2_empty_log_file()
{
return (why2_log_file)
{
INVALID_FILE,
NULL
};
}
why2_decrypted_output why2_empty_decrypted_output()
{
return (why2_decrypted_output)
{
NULL,
0
};
}

View File

@ -1,5 +1,5 @@
{ {
"active": "v5.0", "active": "v4.3.2",
"deprecated": "deprecated":
[ [
@ -22,7 +22,6 @@
"v4.2", "v4.2",
"v4.2.1", "v4.2.1",
"v4.3", "v4.3",
"v4.3.1", "v4.3.1"
"v4.3.2"
] ]
} }