Compare commits

..

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

40 changed files with 503 additions and 1134 deletions

View File

@ -25,10 +25,6 @@ on:
permissions: permissions:
contents: read contents: read
env:
bramborak: ${{ secrets.BRAMBORAK }}
jobs: jobs:
codacy-security-scan: codacy-security-scan:
permissions: permissions:
@ -38,13 +34,11 @@ jobs:
name: Codacy Security Scan name: Codacy Security Scan
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- if: env.bramborak == 'ted jsem tam mel jednu slapku' # Ensure this runs only on GitHub - name: Checkout code
name: Checkout code
uses: actions/checkout@v3 uses: actions/checkout@v3
- if: env.bramborak == 'ted jsem tam mel jednu slapku' # Ensure this runs only on GitHub - name: Run Codacy Analysis
name: Run Codacy Analysis uses: codacy/codacy-analysis-cli-action@d840f886c4bd4edc059706d09c6a1586111c540b
uses: codacy/codacy-analysis-cli-action@master
with: with:
project-token: ${{ secrets.CODACY_PROJECT_TOKEN }} project-token: ${{ secrets.CODACY_PROJECT_TOKEN }}
verbose: true verbose: true
@ -53,8 +47,7 @@ jobs:
gh-code-scanning-compat: true gh-code-scanning-compat: true
max-allowed-issues: 2147483647 max-allowed-issues: 2147483647
- if: env.bramborak == 'ted jsem tam mel jednu slapku' # Ensure this runs only on GitHub - name: Upload results file
name: Upload results file
uses: github/codeql-action/upload-sarif@v2 uses: github/codeql-action/upload-sarif@v2
with: with:
sarif_file: results.sarif sarif_file: results.sarif

View File

@ -34,7 +34,7 @@ jobs:
- os: ubuntu-latest - os: ubuntu-latest
client: ./out/why2-chat-client client: ./out/why2-chat-client
server: ./out/why2-chat-server server: ./out/why2-chat-server
configure: ./configure.sh configure: configure.sh
steps: steps:
- name: Checkout repository - name: Checkout repository
@ -45,8 +45,8 @@ jobs:
- if: matrix.os == 'ubuntu-latest' - if: matrix.os == 'ubuntu-latest'
name: Update packages name: Update packages
run: | run: |
sudo apt-get update sudo apt update
# sudo apt-get upgrade # sudo apt upgrade
- name: Permissions - name: Permissions
run: chmod +x ${{ matrix.configure }} run: chmod +x ${{ matrix.configure }}
@ -54,9 +54,6 @@ jobs:
- name: Preparation - name: Preparation
run: sudo ./${{ matrix.configure }} run: sudo ./${{ matrix.configure }}
- name: Set up Rust # Normally works with configure.sh, but gitea has some beef with cargo idk
uses: dtolnay/rust-toolchain@stable
- name: Install WHY2 - name: Install WHY2
run: make install run: make install
@ -64,13 +61,13 @@ jobs:
run: make build_chat run: make build_chat
- name: Upload Client - name: Upload Client
uses: actions/upload-artifact@v3 uses: actions/upload-artifact@v4
with: with:
name: WHY2 Chat Client name: WHY2 Chat Client
path: ${{ matrix.client }} path: ${{ matrix.client }}
- name: Upload Server - name: Upload Server
uses: actions/upload-artifact@v3 uses: actions/upload-artifact@v4
with: with:
name: WHY2 Chat Server name: WHY2 Chat Server
path: ${{ matrix.server }} path: ${{ matrix.server }}

View File

@ -33,9 +33,8 @@ jobs:
include: include:
- os: ubuntu-latest - os: ubuntu-latest
output: ./out/why2-core-test output: ./out/why2-core-test
gdb: gdb -ex "run" -ex "quit" --batch
valgrind: valgrind --leak-check=full --show-leak-kinds=reachable --track-origins=yes -s valgrind: valgrind --leak-check=full --show-leak-kinds=reachable --track-origins=yes -s
configure: ./configure.sh configure: configure.sh
app: why2 app: why2
steps: steps:
@ -47,8 +46,8 @@ jobs:
- if: matrix.os == 'ubuntu-latest' - if: matrix.os == 'ubuntu-latest'
name: Update packages name: Update packages
run: | run: |
sudo apt-get update sudo apt update
# sudo apt-get upgrade # sudo apt upgrade
- name: Permissions - name: Permissions
run: chmod +x ${{ matrix.configure }} run: chmod +x ${{ matrix.configure }}
@ -57,10 +56,7 @@ jobs:
run: sudo ./${{ matrix.configure }} run: sudo ./${{ matrix.configure }}
- name: Install Valgrind - name: Install Valgrind
run: sudo apt-get install valgrind -y run: sudo apt install valgrind
- name: Set up Rust # Normally works with configure.sh, but gitea has some beef with cargo idk
uses: dtolnay/rust-toolchain@stable
- name: Install WHY2 - name: Install WHY2
run: make install run: make install
@ -69,10 +65,10 @@ jobs:
run: make test_core run: make test_core
- name: Test Lib - name: Test Lib
run: ${{ matrix.gdb }} ${{ matrix.output }} run: ./${{ matrix.output }}
- name: Test App - name: Test App
run: ${{ matrix.gdb }} ${{ matrix.app }} run: ${{ matrix.app }}
- name: Test Lib by Valgrind - name: Test Lib by Valgrind
run: ${{ matrix.valgrind }} ${{ matrix.output }} run: ${{ matrix.valgrind }} ${{ matrix.output }}

View File

@ -33,8 +33,7 @@ jobs:
include: include:
- os: ubuntu-latest - os: ubuntu-latest
output: ./out/why2-logger-test output: ./out/why2-logger-test
gdb: gdb -ex "run" -ex "quit" --batch configure: configure.sh
configure: ./configure.sh
valgrind: valgrind --leak-check=full --show-leak-kinds=reachable --track-origins=yes -s valgrind: valgrind --leak-check=full --show-leak-kinds=reachable --track-origins=yes -s
app: why2-logger app: why2-logger
@ -47,8 +46,8 @@ jobs:
- if: matrix.os == 'ubuntu-latest' - if: matrix.os == 'ubuntu-latest'
name: Update packages name: Update packages
run: | run: |
sudo apt-get update sudo apt update
# sudo apt-get upgrade # sudo apt upgrade
- name: Permissions - name: Permissions
run: chmod +x ${{ matrix.configure }} run: chmod +x ${{ matrix.configure }}
@ -57,10 +56,7 @@ jobs:
run: sudo ./${{ matrix.configure }} run: sudo ./${{ matrix.configure }}
- name: Install Valgrind - name: Install Valgrind
run: sudo apt-get install valgrind -y run: sudo apt install valgrind
- name: Set up Rust # Normally works with configure.sh, but gitea has some beef with cargo idk
uses: dtolnay/rust-toolchain@stable
- name: Install WHY2 - name: Install WHY2
run: make install run: make install
@ -69,10 +65,10 @@ jobs:
run: make test_logger run: make test_logger
- name: Test Lib - name: Test Lib
run: ${{ matrix.gdb }} ${{ matrix.output }} run: ./${{ matrix.output }}
- name: Test App - name: Test App
run: ${{ matrix.gdb }} ${{ matrix.app }} run: ${{ matrix.app }}
- name: Test Lib by Valgrind - name: Test Lib by Valgrind
run: ${{ matrix.valgrind }} ${{ matrix.output }} run: ${{ matrix.valgrind }} ${{ matrix.output }}

View File

@ -30,9 +30,8 @@ jobs:
os: [ ubuntu-latest ] os: [ ubuntu-latest ]
include: include:
- os: ubuntu-latest - os: ubuntu-latest
gdb: gdb -ex "run" -ex "quit" --batch configure: configure.sh
configure: ./configure.sh test: test
test: ./test
steps: steps:
- name: Checkout repository - name: Checkout repository
@ -43,22 +42,16 @@ jobs:
- if: matrix.os == 'ubuntu-latest' - if: matrix.os == 'ubuntu-latest'
name: Update packages name: Update packages
run: | run: |
sudo apt-get update sudo apt update
# sudo apt-get upgrade # sudo apt upgrade
- name: Permissions - name: Permissions
run: | run: |
chmod +x ${{ matrix.configure }} chmod +x ${{ matrix.configure }}
- name: Install GDB
run: sudo apt-get install gdb -y
- name: Preparation - name: Preparation
run: sudo ./${{ matrix.configure }} run: sudo ./${{ matrix.configure }}
- name: Set up Rust # Normally works with configure.sh, but gitea has some beef with cargo idk
uses: dtolnay/rust-toolchain@stable
- name: Install WHY2 - name: Install WHY2
run: make install run: make install
@ -69,4 +62,4 @@ jobs:
run: cc ${{ matrix.test }}.c -lwhy2 -Wall -o ${{ matrix.test }} run: cc ${{ matrix.test }}.c -lwhy2 -Wall -o ${{ matrix.test }}
- name: Run test - name: Run test
run: ${{ matrix.gdb }} ./${{ matrix.test }} run: ./${{ matrix.test }}

1
.gitignore vendored
View File

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

View File

@ -22,17 +22,15 @@ variables:
LOGGER_OUTPUT: "./out/why2-logger-test" LOGGER_OUTPUT: "./out/why2-logger-test"
LOGGER_APP: "why2-logger" LOGGER_APP: "why2-logger"
VALGRIND: "valgrind --leak-check=full --show-leak-kinds=reachable --track-origins=yes -s" VALGRIND: "valgrind --leak-check=full --show-leak-kinds=reachable --track-origins=yes -s"
CONFIGURE: "./configure.sh"
NEEDED_STUFF: "sudo lsb-release gdb"
why2-chat-build: why2-chat-build:
stage: build stage: build
image: rust:latest # Fixes cargo installation problems in ./configure.sh image: rust:latest # Fixes cargo installation problems in ./configure.sh
script: script:
- apt-get update # Update repos - apt update # Update repos
- apt-get install $NEEDED_STUFF -y # Install needed stuff - apt install sudo lsb-release -y # Install needed stuff
- chmod +x $CONFIGURE # Permissions - chmod +x configure.sh # Permissions
- sudo $CONFIGURE # Preparation - sudo ./configure.sh # Preparation
- make install BYPASS_CHECK=true # Install WHY2 - make install BYPASS_CHECK=true # Install WHY2
- make build_chat # Build Chat - make build_chat # Build Chat
artifacts: artifacts:
@ -44,39 +42,39 @@ why2-core-test:
stage: build stage: build
image: rust:latest image: rust:latest
script: script:
- apt-get update # Update repos - apt update # Update repos
- apt-get install $NEEDED_STUFF valgrind -y # Install needed stuff - apt install sudo lsb-release valgrind -y # Install needed stuff
- chmod +x $CONFIGURE # Permissions - chmod +x configure.sh # Permissions
- sudo $CONFIGURE # Preparation - sudo ./configure.sh # Preparation
- make install BYPASS_CHECK=true # Install WHY2 - make install BYPASS_CHECK=true # Install WHY2
- make test_core # Build WHY2 Test - make test_core # Build WHY2 Test
- gdb -ex "run" -ex "quit" --batch $CORE_OUTPUT # Test Lib - ./$CORE_OUTPUT # Test Lib
- gdb -ex "run" -ex "quit" --batch $CORE_APP # Test App - $CORE_APP # Test App
- $VALGRIND $CORE_OUTPUT # Test Lib by Valgrind - $VALGRIND $CORE_OUTPUT # Test Lib by Valgrind
why2-logger-test: why2-logger-test:
stage: build stage: build
image: rust:latest image: rust:latest
script: script:
- apt-get update # Update repos - apt update # Update repos
- apt-get install $NEEDED_STUFF valgrind -y # Install needed stuff - apt install sudo lsb-release valgrind -y # Install needed stuff
- chmod +x $CONFIGURE # Permissions - chmod +x configure.sh # Permissions
- sudo $CONFIGURE # Preparation - sudo ./configure.sh # Preparation
- make install BYPASS_CHECK=true # Install WHY2 - make install BYPASS_CHECK=true # Install WHY2
- make test_logger # Build WHY2 Test - make test_logger # Build WHY2 Test
- gdb -ex "run" -ex "quit" --batch $LOGGER_OUTPUT # Test Lib - ./$LOGGER_OUTPUT # Test Lib
- gdb -ex "run" -ex "quit" --batch $LOGGER_APP # Test App - $LOGGER_APP # Test App
- $VALGRIND $LOGGER_OUTPUT # Test Lib by Valgrind - $VALGRIND $LOGGER_OUTPUT # Test Lib by Valgrind
why2-project: why2-project:
stage: build stage: build
image: rust:latest image: rust:latest
script: script:
- apt-get update # Update repos - apt update # Update repos
- apt-get install $NEEDED_STUFF -y # Install needed stuff - apt install sudo lsb-release -y # Install needed stuff
- chmod +x $CONFIGURE # Permissions - chmod +x configure.sh # Permissions
- sudo $CONFIGURE # Preparation - sudo ./configure.sh # Preparation
- make install BYPASS_CHECK=true # Install WHY2 - make install BYPASS_CHECK=true # Install WHY2
- curl -Lo ./test.c https://gist.github.com/ENGO150/d8419b6c31ffb68ebb930a5b41af8c73/raw # Download WHY2 test project - 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 - cc test.c -lwhy2 -Wall -o test # Build WHY2 project
- $GDB ./test # Run Test - ./test # Run Test

View File

@ -1,6 +1,5 @@
- https://github.com/ENGO150/WHY2 - https://github.com/ENGO150/WHY2
- https://gitlab.com/ENGO150/why2 - https://gitlab.com/ENGO150/why2
- https://gitlab.spseplzen.cz/smejkalv/why2 - https://gitlab.spseplzen.cz/smejkalv/why2
- https://gitea.coquette.baby/ENGO150/WHY2 # Private mirror
Contact me for access to private mirror. Contact me for access to private mirror.

View File

@ -23,8 +23,8 @@ CFLAGS=-Wall -Wextra -Werror -Wcomment -Wformat -Wformat-security -Wmain -Wnonnu
# Output Files # Output Files
PROJECT_NAME=why2 PROJECT_NAME=why2
OUTPUT=./out OUTPUT=out
LOGS=./logs LOGS=logs
OUTPUT_TEST_CORE=$(OUTPUT)/$(PROJECT_NAME)-core-test OUTPUT_TEST_CORE=$(OUTPUT)/$(PROJECT_NAME)-core-test
OUTPUT_APP_CORE=$(OUTPUT)/$(PROJECT_NAME)-core-app OUTPUT_APP_CORE=$(OUTPUT)/$(PROJECT_NAME)-core-app
@ -59,7 +59,7 @@ TEST_LOGGER=./src/logger/lib/test/main.c
LIBS_LOGGER=$(LIB_CORE) LIBS_LOGGER=$(LIB_CORE)
LIB_LOGGER=-l$(PROJECT_NAME)-logger LIB_LOGGER=-l$(PROJECT_NAME)-logger
LIBS_LIB_CHAT=$(LIB_CORE) -lpthread -lcrypto LIBS_LIB_CHAT=$(LIB_CORE) -lpthread -lgmp
LIB_CHAT=-l$(PROJECT_NAME)-chat LIB_CHAT=-l$(PROJECT_NAME)-chat
LIB_CHAT_CONFIG=$(LIB_CHAT)-config LIB_CHAT_CONFIG=$(LIB_CHAT)-config
LIBS_CHAT=$(LIB_CHAT) $(LIBS_LIB_CHAT) $(LIB_CHAT_CONFIG) LIBS_CHAT=$(LIB_CHAT) $(LIBS_LIB_CHAT) $(LIB_CHAT_CONFIG)
@ -81,6 +81,7 @@ check_root:
ifneq ($(BYPASS_CHECK),true) ifneq ($(BYPASS_CHECK),true)
@if [ "$(shell id -u)" = 0 ]; then\ @if [ "$(shell id -u)" = 0 ]; then\
echo "Do not run install rules as root.";\ echo "Do not run install rules as root.";\
exit 1;\
fi fi
endif endif

View File

@ -17,30 +17,22 @@
# along with this program. If not, see <https://www.gnu.org/licenses/>. # along with this program. If not, see <https://www.gnu.org/licenses/>.
# Get linux distro # Get linux distro
DISTRO=$(grep ^ID_LIKE= /etc/os-release | cut -d= -f2 | tr -d '"') DISTRO=$(lsb_release -is)
if [ -e $DISTRO ]
then
DISTRO=$(grep ^ID= /etc/os-release | cut -d= -f2 | tr -d '"')
fi
if [[ $(id -u) != "0" ]] && [[ $1 != "force" ]] if [[ $(id -u) != "0" ]] && [[ $1 != "force" ]]; then
then
echo "You must run this script as root! (To skip this, run with 'force' arg: \"./configure.sh force\")" echo "You must run this script as root! (To skip this, run with 'force' arg: \"./configure.sh force\")"
exit 1 exit 1
fi fi
COMMON="gcc make tmux curl" COMMON="gcc make tmux curl"
ARCH_GENTOO_COMMON="$COMMON json-c libgit2 openssl" ARCH_GENTOO_COMMON="$COMMON json-c libgit2 gmp"
# Get COMMAND # Get COMMAND
if [[ $DISTRO == "arch" ]] if [[ $DISTRO == "Arch" ]]; then
then
COMMAND="pacman -S --needed --noconfirm $ARCH_GENTOO_COMMON" COMMAND="pacman -S --needed --noconfirm $ARCH_GENTOO_COMMON"
elif [[ $DISTRO == "debian" ]] elif [[ $DISTRO == "Ubuntu" ]] || [[ $DISTRO == "Debian" ]]; then
then COMMAND="apt install -y $COMMON libjson-c-dev libcurl4-nss-dev libgit2-dev libgmp-dev"
COMMAND="apt-get install -y $COMMON libjson-c-dev libcurl4-openssl-dev libgit2-dev libssl-dev" elif [[ $DISTRO == "Gentoo" ]]; then
elif [[ $DISTRO == "gentoo" ]]
then
COMMAND="emerge -vn $ARCH_GENTOO_COMMON" COMMAND="emerge -vn $ARCH_GENTOO_COMMON"
# Add # Add
@ -68,8 +60,7 @@ fi
$COMMAND $COMMAND
# Install Rust # Install Rust
if ! [ -x "$(command -v cargo)" ] if ! [ -x "$(command -v cargo)" ]; then
then
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y # Install Rust and components curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y # Install Rust and components
source "$HOME/.cargo/env" source "$HOME/.cargo/env"
fi fi

View File

@ -37,14 +37,11 @@ void why2_chat_init_client_config(void); //Dementia is a term used to describe a
char *why2_toml_read(const char* path, const char* key); //READ key FROM path TOML FILE 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 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 why2_bool why2_toml_contains(const char *path, const char *key); //CHECK IF path CONTAINS key
why2_bool why2_toml_equals(const char *path, const char *key, const char *value); //CHECK IF key IN path IS EQUAL TO value
void why2_toml_read_free(char* s); //DEALLOCATE THE READ VALUE 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_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* char *why2_chat_client_config(char *key); //hihi, *grabs shotgun quietly*
char *why2_get_server_users_path(void); //RETURNS WHY2_CHAT_CONFIG_SERVER_USERS LOCATION
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif

View File

@ -23,27 +23,26 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
extern "C" { extern "C" {
#endif #endif
#include <openssl/types.h>
#include <why2/flags.h>
#include <why2/chat/config.h> #include <why2/chat/config.h>
//MACROS //MACROS
#define WHY2_CHAT_ECC NID_secp521r1 //CURVE NAME #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_KEY_LOCATION WHY2_CONFIG_DIR "/keys" //KEYS LOCATION
#define WHY2_CHAT_KEY "secp521r1.pem" #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
#define WHY2_CHAT_BASE64_LENGTH_DELIMITER ':' //SEPARATES BASE64 FROM LENGTH (YnJhbWJvcmFrCg==:9) void why2_chat_init_keys(void); //INIT (POSSIBLY GENERATE) RSA KEYS
void why2_chat_init_keys(void); //INIT (POSSIBLY GENERATE) ECC KEYS
void why2_chat_deallocate_keys(void); //DEALLOCATE :) (NO SLUR HERE) void why2_chat_deallocate_keys(void); //DEALLOCATE :) (NO SLUR HERE)
char *why2_chat_ecc_sign(char *message); //SIGN message WITH ECC KEY char *why2_get_chat_modulus(void); //GET THE RSA MODULUS
why2_bool why2_chat_ecc_verify_signature(char *message, char *signature, EVP_PKEY *key); char *why2_get_chat_d(void); //GET THE RSA d
char *why2_sha256(char *input); //HASH input USING SHA256 AND RETURN IN STRING 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 #ifdef __cplusplus
} }

View File

@ -23,8 +23,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
extern "C" { extern "C" {
#endif #endif
#include <why2/flags.h>
//MACROS //MACROS
#define WHY2_SA struct sockaddr #define WHY2_SA struct sockaddr
#define WHY2_CHAT_SERVER_PORT 1204 //PORT #define WHY2_CHAT_SERVER_PORT 1204 //PORT
@ -42,8 +40,6 @@ extern "C" {
#define WHY2_CHAT_CODE_LIST_SERVER "code_004" //SAME AS WHY2_CHAT_CODE_LIST BUT BACK TO THE CLIENT #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_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 #define WHY2_CHAT_CODE_PM_SERVER "code_006" //SAME AS WHY2_CHAT_CODE_PM BUT BACK TO THE CLIENT
#define WHY2_CHAT_CODE_ENTER_PASSWORD "code_007" //RECEIVE PASSWORD FROM USER
#define WHY2_CHAT_CODE_INVALID_PASSWORD "code_008"//🌸ꗥ~ꗥ🌸 𝐢 𝐡𝐚𝐭𝐞 𝐲𝐨𝐮 🌸ꗥ~ꗥ🌸
//(CLIENT -> SERVER) CODES //(CLIENT -> SERVER) CODES
#define WHY2_CHAT_CODE_EXIT "code_999" //TELL SERVER YOU ARE ENDING COMMUNICATION #define WHY2_CHAT_CODE_EXIT "code_999" //TELL SERVER YOU ARE ENDING COMMUNICATION
@ -56,16 +52,14 @@ extern "C" {
#define WHY2_CHAT_COMMAND_EXIT "exit" //QUIT THE PROGRAM CMD #define WHY2_CHAT_COMMAND_EXIT "exit" //QUIT THE PROGRAM CMD
#define WHY2_CHAT_COMMAND_HELP "help" //PRINT ALL COMMANDS #define WHY2_CHAT_COMMAND_HELP "help" //PRINT ALL COMMANDS
#define WHY2_CHAT_COMMAND_LIST "list" //LIST ALL CONNECTIONS #define WHY2_CHAT_COMMAND_LIST "list" //LIST ALL CONNECTIONS
#define WHY2_CHAT_COMMAND_DM "dm" //DIRECT (UNENCRYPTED) MESSAGES #define WHY2_CHAT_COMMAND_PM "pm" //PRIVATE MESSAGES
#define WHY2_CHAT_COMMAND_VERSION "version" //COMPARE CLIENT VERSION AND SERVER VERSION #define WHY2_CHAT_COMMAND_VERSION "version" //COMPARE CLIENT VERSION AND SERVER VERSION
#define WHY2_CHAT_COMMAND_PM "pm" //PRIVATE (ENCRYPTED) MESSAGES
//SHORTCUTS CAUSE I'M LAZY BITCH //SHORTCUTS CAUSE I'M LAZY BITCH
#define WHY2_CHAT_CODE_SSQC WHY2_CHAT_CODE_SERVER_SIDE_QUIT_COMMUNICATION #define WHY2_CHAT_CODE_SSQC WHY2_CHAT_CODE_SERVER_SIDE_QUIT_COMMUNICATION
//FUNCTIONS char *why2_chat_client_get_server_exit_cmd(); //GETTER AND SETTER FOR !exit FROM SERVER
void __why2_set_asking_password(why2_bool value); //IF HASH SHOULD BE SENT INSTEAD OF NORMAL MESSAGE void why2_chat_client_set_server_exit_cmd(char *cmd);
why2_bool __why2_get_asking_password();
#ifdef __cplusplus #ifdef __cplusplus
} }

View File

@ -26,7 +26,6 @@ extern "C" {
#include <why2/flags.h> //TODO: fuck this #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_send_socket(char *text, char *username, int socket); //send socket.... wtf did you expect
void why2_send_socket_code(char *params, char *username, int socket, char *code); //SEND SOCKET BUT WITH CODE
void *why2_communicate_thread(void *arg); //COMMUNICATION THREAD void *why2_communicate_thread(void *arg); //COMMUNICATION THREAD
void *why2_accept_thread(void *socket); //LOOP ACCEPTING CONNECTIONS void *why2_accept_thread(void *socket); //LOOP ACCEPTING CONNECTIONS
void why2_clean_connections(void); //CLOSE EVERY CONNECTION void why2_clean_connections(void); //CLOSE EVERY CONNECTION

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_CRYPTO_H
#define WHY2_CRYPTO_H
#ifdef __cplusplus
extern "C" {
#endif
#include <sys/types.h>
#include <why2/flags.h>
//MACROS
#define WHY2_SUM_SEGMENT_SIZE 32 //SEGMENT SIZE FOR CALCULATING SUM
#define WHY2_SUM_BASE_PRIME 31 //PRIME FOR SUM BASE
#define WHY2_SUM_MOD_PRIME 4294967295UL //PRIME FOR SUM MODULUS; 2^32 - 1
#define WHY2_RECOMMENDED_PADDING_RATE(input_len) ((unsigned long) input_len / 3)
#define WHY2_PADDING_NONZERO_TRIES 1024 //HOW MANY RANDOM NUMBERS TO TRY TO GENERATE WHEN PREVENTING 0s
//FUNCTIONS
unsigned long long why2_sum_segment(char *input); //CALCULATE SUM++ FOR input; USED FOR PADDING SEED
why2_bool why2_random(void *dest, size_t size); //WRITE CRYPTO-SECURE RANDOM NUMBER INTO dest
void why2_seed_random(unsigned long seed); //SEED why2_seeded_random OUTPUT
int why2_seeded_random(); //GENERATE RANDOM NUMBER BASED ON SEED PASSED IN why2_seed_random
#ifdef __cplusplus
}
#endif
#endif

View File

@ -25,7 +25,7 @@ extern "C" {
#include <why2/flags.h> #include <why2/flags.h>
why2_output_flags why2_decrypt_text(char *text, char *key); //TEXT from WILL BE DECRYPTED WITH KEY AND RETURNED why2_output_flags why2_decrypt_text(char *text, char *key_new); //TEXT from WILL BE DECRYPTED WITH KEY AND RETURNED
#ifdef __cplusplus #ifdef __cplusplus
} }

View File

@ -25,7 +25,7 @@ extern "C" {
#include <why2/flags.h> #include <why2/flags.h>
why2_output_flags why2_encrypt_text(char *text, char *key); //TEXT from WILL BE ENCRYPTED WITH key AND RETURNED why2_output_flags why2_encrypt_text(char *text, char *key_new); //TEXT from WILL BE ENCRYPTED WITH KEY AND RETURNED
#ifdef __cplusplus #ifdef __cplusplus
} }

View File

@ -34,13 +34,12 @@ enum WHY2_EXIT_CODES //exit codes you fucking idiot
}; };
//THESE ARE LEGACY VERSIONS FOR GENERATING tkch, SO YOU CAN DECRYPT OLD TEXT //THESE ARE 'HISTORIC' VERSION FOR GENERATING tkch, SO YOU CAN DECRYPT OLD TEXT
enum WHY2_TEXT_KEY_CHAIN_VERSIONS enum WHY2_TEXT_KEY_CHAIN_VERSIONS
{ {
WHY2_v1, //FIRST VERSION. Replaced on May 28th 17:45:26 2022 UTC in commit 0d64f4fa7c37f0b57914db902258e279a71c7f9a. 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_v2, //SECOND VERSION. Replaced on July 11th 17:12:41 2022 UTC in commit 0f01cde0f1e1a9210f4eef7b949e6d247072d3a6.
WHY2_v3, //THIRD VERSION. Replaced on Nov 17 19:55:13 2024 UTC in commit f917140ae54e4f5e601a089fbbea33817233e534. WHY2_v3 //THIRD VERSION. THE LATEST ONE
WHY2_v4 //LATEST VERSION, MOST SECURE (how unexpected)
}; };
enum WHY2_OUTPUT_FORMAT enum WHY2_OUTPUT_FORMAT
@ -51,8 +50,7 @@ enum WHY2_OUTPUT_FORMAT
#define WHY2_VERSION "v5.0" //WHY2_VERSION OF CURRENT BUILD > DO NOT TOUCH THIS < #define WHY2_VERSION "v5.0" //WHY2_VERSION OF CURRENT BUILD > DO NOT TOUCH THIS <
#define WHY2_VERSIONS_URL "https://raw.githubusercontent.com/ENGO150/WHY2/release/versions.json" //URL FOR GETTING versions.json #define WHY2_VERSIONS_URL "https://raw.githubusercontent.com/ENGO150/WHY2/release/versions.json" //URL FOR GETTING versions.json
#define WHY2_USER_CONFIG_DIR "{HOME}/.config" #define WHY2_CONFIG_DIR "/home/{USER}/.config/WHY2"
#define WHY2_CONFIG_DIR WHY2_USER_CONFIG_DIR "/WHY2"
#define WHY2_VERSIONS_NAME WHY2_CONFIG_DIR "/.versions.json" //do I have to explain this? #define WHY2_VERSIONS_NAME WHY2_CONFIG_DIR "/.versions.json" //do I have to explain this?
#define WHY2_UPDATE_URL "https://github.com/ENGO150/WHY2.git" // REPOSITORY URL FOR UPDATES (YOU DON'T SAY) #define WHY2_UPDATE_URL "https://github.com/ENGO150/WHY2.git" // REPOSITORY URL FOR UPDATES (YOU DON'T SAY)
@ -65,7 +63,7 @@ enum WHY2_OUTPUT_FORMAT
#define WHY2_CLEAR_SCREEN "\e[1;1H\e[2J" //TEXT FOR UNIX CLEAR SCREEN #define WHY2_CLEAR_SCREEN "\e[1;1H\e[2J" //TEXT FOR UNIX CLEAR SCREEN
#define WHY2_CURL_TIMEOUT 10 //if you need comment explaining, what the fuck is timeout, don't change WHY2's code, alright? thx, love ya #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_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_DEPRECATED __attribute__((deprecated)) //SAME COMMENT AS WHY2_VERSIONS_NAME'S
@ -81,7 +79,6 @@ typedef struct
why2_bool update; //BOOLEAN FOR UPDATING YOUR WHY WHY2_VERSION IF OLD IS USED why2_bool update; //BOOLEAN FOR UPDATING YOUR WHY WHY2_VERSION IF OLD IS USED
enum WHY2_TEXT_KEY_CHAIN_VERSIONS version; //VERSION OF tkch enum WHY2_TEXT_KEY_CHAIN_VERSIONS version; //VERSION OF tkch
enum WHY2_OUTPUT_FORMAT format; //VERSION OF tkch enum WHY2_OUTPUT_FORMAT format; //VERSION OF tkch
unsigned long padding; //HOW MUCH PADDING CHARS TO INSERT
} why2_input_flags; } why2_input_flags;
typedef struct typedef struct
@ -104,20 +101,15 @@ why2_input_flags why2_get_flags(void); //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 why2_output_flags why2_no_output(enum WHY2_EXIT_CODES exit_code); //SAME AS why2_get_default_flags() BUT FOR why2_output_flags
why2_encryption_operation_cb why2_get_encryption_operation(void); //RETURNS FUNCTION WHICH IS USED FOR ENCRYPTION & DECRYPTION why2_encryption_operation_cb why2_get_encryption_operation(void); //RETURNS FUNCTION WHICH IS USED FOR ENCRYPTION & DECRYPTION
why2_bool why2_get_flags_changed(void); why2_bool why2_get_flags_changed(void);
why2_bool why2_get_padding_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_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); char *why2_get_default_memory_identifier(void);
//SETTERS //SETTERS
void why2_set_encryption_separator(char encryption_separator_new); void why2_set_encryption_separator(char encryption_separator_new);
void why2_set_key_length(int keyLengthNew); void why2_set_key_length(int keyLengthNew);
void why2_set_flags(why2_input_flags new_flags); //.... whatcha think? void why2_set_flags(why2_input_flags newFlags); //.... whatcha think?
void __why2_set_flags_anon(why2_input_flags new_flags); //DO NOT CHANGE flags_changed ON USAGE
void why2_set_encryption_operation(why2_encryption_operation_cb newEncryptionOperation); //are you that dumb? 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_set_memory_identifier(char *new_memory_identifier);
void why2_set_padding(unsigned long padding); //SET PADDING RATE WITHOUT REWRITING INPUT FLAGS
void __why2_set_padding_anon(unsigned long padding);
void why2_reset_memory_identifier(void); //hmmm, what could reset mean.... huh void why2_reset_memory_identifier(void); //hmmm, what could reset mean.... huh
#ifdef __cplusplus #ifdef __cplusplus

View File

@ -40,13 +40,10 @@ typedef struct
//FUNCTIONS //FUNCTIONS
void why2_list_push(why2_list_t *list, void *value, unsigned long size); //PUSH ELEMENT TO LIST BACK void why2_list_push(why2_list_t *list, void *value, unsigned long size); //PUSH ELEMENT TO LIST BACK
void why2_list_push_at(why2_list_t *list, unsigned long index, void *value, unsigned long size); //PUSH ELEMENT TO INDEX index of LIST
void why2_list_remove(why2_list_t *list, why2_node_t *node); //REMOVE ELEMENT void why2_list_remove(why2_list_t *list, why2_node_t *node); //REMOVE ELEMENT
void why2_list_remove_at(why2_list_t *list, unsigned long index); //REMOVE ELEMENT WITH INDEX index
void why2_list_remove_back(why2_list_t *list); //REMOVE LAST 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 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 unsigned long why2_list_get_size(why2_list_t *list); //GET SIZE
void why2_list_reverse(why2_list_t *list, unsigned long size); //REVERSES list
#ifdef __cplusplus #ifdef __cplusplus
} }

View File

@ -27,8 +27,7 @@ extern "C" {
void *why2_malloc(unsigned long size); void *why2_malloc(unsigned long size);
void *why2_calloc(unsigned long element, unsigned long size); void *why2_calloc(unsigned long element, unsigned long size);
void *why2_realloc(void *pointer, unsigned long size); //THIS DOESN'T PRESERVE CONTENT OF pointer! void *why2_realloc(void *pointer, unsigned long size);
void *why2_recalloc(void *pointer, unsigned long size, unsigned long block_size); //SAME AS why2_realloc BUT FILLS THE pointer WITH NULL-TERMS
char *why2_strdup(char *string); char *why2_strdup(char *string);

View File

@ -30,7 +30,6 @@ extern "C" {
#endif #endif
//CORE //CORE
#include <why2/crypto.h>
#include <why2/decrypter.h> #include <why2/decrypter.h>
#include <why2/encrypter.h> #include <why2/encrypter.h>
#include <why2/flags.h> #include <why2/flags.h>

View File

@ -46,11 +46,11 @@ void init_config(char *filename)
char *buffer = why2_malloc(strlen(WHY2_CONFIG_DIR) + strlen(filename) + 2); char *buffer = why2_malloc(strlen(WHY2_CONFIG_DIR) + strlen(filename) + 2);
sprintf(buffer, "%s/%s", WHY2_CONFIG_DIR, filename); sprintf(buffer, "%s/%s", WHY2_CONFIG_DIR, filename);
char *path = why2_replace(buffer, "{HOME}", getenv("HOME")); char *path = why2_replace(buffer, "{USER}", getenv("USER"));
if (access(path, R_OK) != 0) //CONFIG DOESN'T EXIST if (access(path, R_OK) != 0) //CONFIG DOESN'T EXIST
{ {
char *config_dir = why2_replace(WHY2_CONFIG_DIR, "{HOME}", getenv("HOME")); char *config_dir = why2_replace(WHY2_CONFIG_DIR, "{USER}", getenv("USER"));
//CREATE CONFIG DIRECTORY //CREATE CONFIG DIRECTORY
mkdir(config_dir, 0700); mkdir(config_dir, 0700);
@ -85,11 +85,11 @@ char *config(char *key, enum CONFIG_TYPES type)
switch (type) //GET path switch (type) //GET path
{ {
case CLIENT: case CLIENT:
path = why2_replace(WHY2_CONFIG_DIR "/" WHY2_CHAT_CONFIG_CLIENT, "{HOME}", getenv("HOME")); path = why2_replace(WHY2_CONFIG_DIR "/" WHY2_CHAT_CONFIG_CLIENT, "{USER}", getenv("USER"));
break; break;
case SERVER: case SERVER:
path = why2_replace(WHY2_CONFIG_DIR "/" WHY2_CHAT_CONFIG_SERVER, "{HOME}", getenv("HOME")); path = why2_replace(WHY2_CONFIG_DIR "/" WHY2_CHAT_CONFIG_SERVER, "{USER}", getenv("USER"));
break; break;
default: default:
@ -113,7 +113,7 @@ void why2_chat_init_server_config(void)
//CHECK FOR USER CONFIG //CHECK FOR USER CONFIG
char *user_pick_username = why2_chat_server_config("user_pick_username"); char *user_pick_username = why2_chat_server_config("user_pick_username");
char *config_path = why2_get_server_users_path(); 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) if (strcmp(user_pick_username, "true") == 0 && access(config_path, R_OK) != 0)
{ {
@ -146,8 +146,3 @@ char *why2_chat_client_config(char *key)
{ {
return config(key, CLIENT); return config(key, CLIENT);
} }
char *why2_get_server_users_path(void)
{
return why2_replace(WHY2_CONFIG_DIR "/" WHY2_CHAT_CONFIG_SERVER_USERS, "{HOME}", getenv("HOME"));
}

View File

@ -24,6 +24,5 @@ communication_time = 300 # Seconds waiting for client message before stopping co
max_username_length = 20 # Maximal username length max_username_length = 20 # Maximal username length
min_username_length = 4 # Minimal 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_username_tries = 3 # Times asking client for username (if client tries to use invalid username)
max_password_tries = 3 # Same as above but for invalid password
max_message_length = 100 # Maximal message length max_message_length = 100 # Maximal message length

View File

@ -34,8 +34,13 @@ use std::
use toml::Value; use toml::Value;
fn toml_read(path_r: String, key_r: String) -> String #[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 //GET FILE CONTENT
let file_raw = match read_to_string(&path_r) let file_raw = match read_to_string(&path_r)
{ {
@ -51,21 +56,15 @@ fn toml_read(path_r: String, key_r: String) -> String
}; };
//GET VALUE BY key_r //GET VALUE BY key_r
match data.get(&key_r) let mut value = match data.get(&key_r)
{ {
Some(value) => value.to_string().replace("\"", "").trim().to_string(), //TRIM AND SHIT Some(value) => value.to_string(),
None => panic!("Key \"{}\" not found in TOML config: {}", key_r, path_r), None => panic!("Key \"{}\" not found in TOML config: {}", key_r, path_r),
} };
}
#[no_mangle] value = value.replace("\"", "").trim().to_string(); //REMOVE QUOTES
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() };
CString::new(toml_read(path_r, key_r)).unwrap().into_raw() //GET CString::new(value).unwrap().into_raw()
} }
#[no_mangle] #[no_mangle]
@ -158,17 +157,6 @@ pub extern "C" fn why2_toml_contains(path: *const c_char, key: *const c_char) ->
data.get(&key_r).is_some() data.get(&key_r).is_some()
} }
#[no_mangle]
pub extern "C" fn why2_toml_equals(path: *const c_char, key: *const c_char, value: *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() };
let value_r = unsafe { CStr::from_ptr(value).to_string_lossy().into_owned() };
toml_read(path_r, key_r) == value_r //RESULT
}
#[no_mangle] #[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 pub extern "C" fn why2_toml_read_free(s: *mut c_char) //BECAUSE THIS IS RUST MODULE I HAVE TO CREATE A DEALLOCATING FUNCTION
{ {

View File

@ -23,194 +23,183 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <string.h> #include <string.h>
#include <unistd.h> #include <unistd.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <sys/random.h>
#include <why2/memory.h> #include <why2/memory.h>
#include <why2/misc.h> #include <why2/misc.h>
#include <openssl/sha.h> #include <gmp.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/ec.h>
EVP_PKEY *keypair = NULL; //KEYPAIR //DO NOT TOUCH THESE PLS :3
char *rsa_modulus = NULL; //THE RSA MODULUS
char *rsa_d = NULL; //THE RSA d
//LOCAL //LOCAL
char *base64_encode(char *message, size_t length) void generate_prime(mpz_t x)
{ {
//VARIABLES //RANDOM
BIO *bio; gmp_randstate_t state;
BIO *b64; gmp_randinit_default(state);
BUF_MEM *buffer_ptr; unsigned long random_buffer; //SEED
char* encoded_message;
//INIT BIOs do
b64 = BIO_new(BIO_f_base64()); {
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); //DISABLE NEWLINES if (getrandom(&random_buffer, sizeof(unsigned long), GRND_NONBLOCK) == -1) why2_die("getrandom fn failed!");
bio = BIO_new(BIO_s_mem());
bio = BIO_push(b64, bio);
//ENCODE //GENERATE RANDOM PRIME USING random_buffer SEED
BIO_write(bio, message, length); gmp_randseed_ui(state, random_buffer);
BIO_flush(bio); mpz_urandomb(x, state, WHY2_CHAT_KEY_BITS);
BIO_get_mem_ptr(bio, &buffer_ptr); mpz_nextprime(x, x);
} while (mpz_probab_prime_p(x, WHY2_CHAT_PRIME_ITERS) == 0); //CHECK FOR PRIME PROBABILITY
//COPY
encoded_message = why2_malloc(buffer_ptr -> length + why2_count_int_length((int) length) + 2);
memcpy(encoded_message, buffer_ptr -> data, buffer_ptr -> length);
sprintf(encoded_message + buffer_ptr -> length, "%c%zu%c", WHY2_CHAT_BASE64_LENGTH_DELIMITER, length, '\0'); //APPEND LENGTH
//DEALLOCATION //DEALLOCATION
BIO_free_all(bio); gmp_randclear(state);
return encoded_message;
} }
char *base64_decode(char *encoded_message, size_t *length) void read_file(FILE *file, char **output)
{ {
//VARIABLES //VARIABLES
BIO *bio; int buffer_size;
BIO *b64; char *buffer;
char *separator_ptr = strrchr(encoded_message, WHY2_CHAT_BASE64_LENGTH_DELIMITER); //GET THE DELIMITER POINTER
*length = strtoull(separator_ptr + 1, NULL, 10);
char* decoded_message = why2_malloc(*length + 1);
int decoded_length;
//INIT BIOs //GET LENGTH
b64 = BIO_new(BIO_f_base64()); fseek(file, 0, SEEK_END);
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); //DISABLE NEWLINES buffer_size = ftell(file);
bio = BIO_new_mem_buf(encoded_message, separator_ptr - encoded_message); rewind(file);
bio = BIO_push(b64, bio);
//DECODE //READ
decoded_length = BIO_read(bio, decoded_message, *length); 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';
//NULL-TERM //ASSIGN OUTPUT
decoded_message[decoded_length] = '\0'; *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 //DEALLOCATION
BIO_free_all(bio); mpz_clears(m, c, n, e, NULL);
return decoded_message; return output;
} }
//GLOBAL //GLOBAL
void why2_chat_init_keys(void) void why2_chat_init_keys(void)
{ {
FILE *key; //KEY FILE //KEY FILES
FILE *public; //TECHNICALLY, PUBLIC KEY CONTAINS ONLY THE MODULUS AND PRIVATE CONTAINS ONLY THE d
FILE *private;
char *path = why2_replace(WHY2_CHAT_KEY_LOCATION, "{HOME}", getenv("HOME")); //GET PATH TO KEY DIR //GET PATH TO KEY DIR
char *key_path = why2_malloc(strlen(path) + strlen(WHY2_CHAT_KEY) + 3); //ALLOCATE THE KEY PATH char *path = why2_replace(WHY2_CHAT_KEY_LOCATION, "{USER}", getenv("USER"));
//GET THE ACTUAL KEY PATH //ALLOCATE THE KEY PATHS
sprintf(key_path, "%s/%s%c", path, WHY2_CHAT_KEY, '\0'); 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);
//CHECK IF KEY EXIST //GET THE ACTUAL KEY PATHS
if (access(path, R_OK) != 0) //NOT FOUND - CREATE IT 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); mkdir(path, 0700);
//SOME USER OUTPUT //SOME USER OUTPUT
printf("No ECC key found.\nGenerating...\n\n"); printf("You are probably running WHY2-Chat for the first time now.\nGenerating RSA keys...\n");
EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL); //CREATE CTX //VARIABLES
EVP_PKEY_keygen_init(ctx); //INIT KEYGEN 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);
EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx, WHY2_CHAT_ECC); //SETUP ECC //GENERATE PRIMES
EVP_PKEY_keygen(ctx, &keypair); //GENERATE ECC KEYPAIR generate_prime(p);
generate_prime(q);
//WRITE THE KEYS INTO KEY-FILE //SET e
key = why2_fopen(key_path, "w+"); mpz_set_str(e, WHY2_CHAT_RSA_EXPONENT, 10);
PEM_write_PrivateKey(key, keypair, NULL, NULL, 0, NULL, NULL); //WRITE THE KEY
//DEALLOCATION //GET n
EVP_PKEY_CTX_free(ctx); 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 } else
{ {
key = why2_fopen(key_path, "r"); //OPEN KEY FILE //OPEN FILES
keypair = PEM_read_PrivateKey(key, NULL, NULL, NULL); //LOAD KEYPAIR 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 //DEALLOCATION
why2_deallocate(path); why2_deallocate(path);
why2_deallocate(key_path); why2_deallocate(public_path);
why2_deallocate(key); why2_deallocate(private_path);
} why2_deallocate(public);
why2_deallocate(private);
char *why2_chat_ecc_sign(char *message)
{
//VARIABLES
EVP_MD_CTX *mdctx = NULL; //SIGNING CONTEXT
size_t siglen;
char *sig; //SIGNATURE
char *encoded_sig; //FINAL (ENCODED) SIGNATURE
//INIT mdctx
mdctx = EVP_MD_CTX_new();
EVP_DigestSignInit(mdctx, NULL, EVP_sha256(), NULL, keypair);
EVP_DigestSignUpdate(mdctx, message, strlen(message)); //UPDATE MESSAGE TO SIGN
EVP_DigestSignFinal(mdctx, NULL, &siglen); //COUNT LENGTH
//GENERATE SIGNATURE
sig = why2_malloc(siglen); //ALLOCATE SIGNATURE
EVP_DigestSignFinal(mdctx, (unsigned char*) sig, &siglen);
encoded_sig = base64_encode(sig, siglen); //CONVERT sig TO BASE64
//DEALLOCATION
why2_deallocate(sig);
EVP_MD_CTX_free(mdctx);
return encoded_sig;
}
why2_bool why2_chat_ecc_verify_signature(char *message, char *signature, EVP_PKEY *key)
{
//VARIABLES
size_t length;
char *decoded_signature = base64_decode(signature, &length); //DECODE SIGNATURE
why2_bool returning;
//INIT CONTEXT
EVP_MD_CTX* ctx = EVP_MD_CTX_new();
//INIT VERIFICATION CONTEXT
EVP_DigestVerifyInit(ctx, NULL, EVP_sha256(), NULL, key);
//VERIFY MESSAGE
EVP_DigestVerifyUpdate(ctx, message, strlen(message));
returning = EVP_DigestVerifyFinal(ctx, (unsigned char*) decoded_signature, length) == 1;
//DEALLOCATION
EVP_MD_CTX_free(ctx);
why2_deallocate(decoded_signature);
return returning;
} }
void why2_chat_deallocate_keys(void) void why2_chat_deallocate_keys(void)
{ {
//DEALLOCATE THE pkey why2_deallocate(rsa_modulus);
EVP_PKEY_free(keypair); why2_deallocate(rsa_d);
} }
char *why2_sha256(char *input) char *why2_get_chat_modulus(void)
{ {
unsigned char *output = why2_malloc(SHA256_DIGEST_LENGTH + 1); return rsa_modulus;
char *formatted_output = why2_malloc(SHA256_DIGEST_LENGTH * 2 + 2); }
SHA256((unsigned char*) input, strlen(input), output); char *why2_get_chat_d(void)
//SAVE AS STRING IN HEX
for (int i = 0; i < SHA256_DIGEST_LENGTH; i++)
{ {
sprintf(formatted_output + (i * 2), "%02x", output[i]); return rsa_d;
} }
formatted_output[SHA256_DIGEST_LENGTH * 2] = '\0';
//DEALLOCATION char *why2_chat_rsa_pub_encrypt(char *to_encrypt)
why2_deallocate(output); {
return exp_mod(to_encrypt, WHY2_CHAT_RSA_EXPONENT);
return formatted_output; }
char *why2_chat_rsa_pri_decrypt(char *to_decrypt)
{
return exp_mod(to_decrypt, why2_get_chat_d());
} }

View File

@ -1,47 +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/flags.h>
#include <unistd.h>
#include <termios.h>
why2_bool asking_password = 0;
void __why2_set_asking_password(why2_bool value)
{
asking_password = value;
struct termios tty;
tcgetattr(STDIN_FILENO, &tty); //GET ATTRS
if (!value)
{
tty.c_lflag |= ECHO; //DISABLE
} else
{
tty.c_lflag &= ~ECHO; //ENABLE
}
tcsetattr(STDIN_FILENO, TCSANOW, &tty); //SET ATTRS
}
why2_bool __why2_get_asking_password()
{
return asking_password;
}

View File

@ -43,7 +43,7 @@ void exit_client(WHY2_UNUSED int i) //guess what
if (exited) return; if (exited) return;
exited = 1; exited = 1;
why2_send_socket_code(NULL, NULL, listen_socket, WHY2_CHAT_CODE_EXIT); why2_send_socket(WHY2_CHAT_CODE_EXIT, NULL, listen_socket);
} }
why2_bool command(char *input, char *command, char **arg) why2_bool command(char *input, char *command, char **arg)
@ -98,7 +98,7 @@ int main(void)
why2_check_version(); //CHECK FOR UPDATES why2_check_version(); //CHECK FOR UPDATES
why2_chat_init_client_config(); //CREATE client.toml CONFIGURATION why2_chat_init_client_config(); //CREATE client.toml CONFIGURATION
why2_chat_init_keys(); //CREATE ECC KEY why2_chat_init_keys(); //CREATE RSA KEYS
listen_socket = socket(AF_INET, SOCK_STREAM, 0); //CREATE SERVER SOCKET listen_socket = socket(AF_INET, SOCK_STREAM, 0); //CREATE SERVER SOCKET
char *line = NULL; char *line = NULL;
@ -188,18 +188,17 @@ int main(void)
"\nCommands:\n---------\n%s\n\n>>> ", "\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_HELP "\t\tPrints out all the commands. :)\n"
WHY2_CHAT_COMMAND_PREFIX WHY2_CHAT_COMMAND_DM " <ID> <MSG>\tSends direct message to user.\n" WHY2_CHAT_COMMAND_PREFIX WHY2_CHAT_COMMAND_PM " <ID> <MSG>\tSends private message to user.\n"
WHY2_CHAT_COMMAND_PREFIX WHY2_CHAT_COMMAND_PM " <ID> <MSG>\tSends encrypted message to user.\n" //TODO: Implement
WHY2_CHAT_COMMAND_PREFIX WHY2_CHAT_COMMAND_LIST "\t\tLists all users and their IDs.\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_VERSION "\tCheck server version.\n"
WHY2_CHAT_COMMAND_PREFIX WHY2_CHAT_COMMAND_EXIT "\t\tExits the program." WHY2_CHAT_COMMAND_PREFIX WHY2_CHAT_COMMAND_EXIT "\t\tExits the program."
); );
fflush(stdout); fflush(stdout);
} else if (command(line, WHY2_CHAT_COMMAND_DM, &cmd_arg)) } else if (command(line, WHY2_CHAT_COMMAND_PM, &cmd_arg))
{ {
char *id; //PM RECEIVER char *id; //PM RECEIVER
char *msg; //something racial WHY2_UNUSED char *msg; //something racial
//CHECK ARGS VALIDITY //CHECK ARGS VALIDITY
why2_bool valid_param = cmd_arg != NULL && strlen(cmd_arg) >= 3; why2_bool valid_param = cmd_arg != NULL && strlen(cmd_arg) >= 3;
@ -241,43 +240,27 @@ int main(void)
} }
//BUILD MESSAGE TO SEND TO SERVER //BUILD MESSAGE TO SEND TO SERVER
char *final_message = why2_malloc(strlen(id) + strlen(msg) + 2); char *final_message = why2_malloc(strlen(WHY2_CHAT_CODE_PM) + strlen(id) + strlen(msg) + 3);
sprintf(final_message, "%s;%s%c", id, msg, '\0'); sprintf(final_message, WHY2_CHAT_CODE_PM ";%s;%s%c", id, msg, '\0');
why2_send_socket_code(final_message, NULL, listen_socket, WHY2_CHAT_CODE_PM); //SEND why2_send_socket(final_message, NULL, listen_socket); //SEND
//DEALLOCATION //DEALLOCATION
why2_deallocate(id); why2_deallocate(id);
why2_deallocate(final_message); why2_deallocate(final_message);
} else if (command(line, WHY2_CHAT_COMMAND_LIST, &cmd_arg)) //LIST CMD } else if (command(line, WHY2_CHAT_COMMAND_LIST, &cmd_arg)) //LIST CMD
{ {
why2_send_socket_code(NULL, NULL, listen_socket, WHY2_CHAT_CODE_LIST); why2_send_socket(WHY2_CHAT_CODE_LIST, NULL, listen_socket);
} else if (command(line, WHY2_CHAT_COMMAND_VERSION, &cmd_arg)) //VERSION CMD } else if (command(line, WHY2_CHAT_COMMAND_VERSION, &cmd_arg)) //VERSION CMD
{ {
why2_send_socket_code(NULL, NULL, listen_socket, WHY2_CHAT_CODE_VERSION); why2_send_socket(WHY2_CHAT_CODE_VERSION, NULL, listen_socket);
} else } else
{ {
invalid("command"); invalid("command");
} }
} else } else
{
if (__why2_get_asking_password())
{
//REMOVE \n AT THE END OF line
line[strlen(line) - 1] = '\0';
char *hash = why2_sha256(line); //HASHISH
why2_send_socket(hash, NULL, listen_socket); //SEND BUT HASHED
//DEALLOCATION
why2_deallocate(hash);
__why2_set_asking_password(0);
} 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 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); free(line);
} }
} }

View File

@ -46,7 +46,6 @@ typedef struct _connection_node
pthread_t thread; pthread_t thread;
char *username; char *username;
unsigned long id; unsigned long id;
char *key; //EACH USER WILL USE DIFFERENT KEY FOR COMMUNICATION
} connection_node_t; //SINGLE LINKED LIST } connection_node_t; //SINGLE LINKED LIST
why2_list_t connection_list = WHY2_LIST_EMPTY; why2_list_t connection_list = WHY2_LIST_EMPTY;
@ -143,7 +142,7 @@ void add_brackets(char **json)
why2_bool is_ascii(char c) why2_bool is_ascii(char c)
{ {
return 32 <= c && c <= 126; return 33 <= c && c <= 126;
} }
void remove_non_ascii(char **text) void remove_non_ascii(char **text)
@ -181,16 +180,34 @@ char *read_socket_raw(int socket)
if (ioctl(socket, FIONREAD, &content_size) < 0 || content_size <= 0) continue; if (ioctl(socket, FIONREAD, &content_size) < 0 || content_size <= 0) continue;
//ALLOCATE //ALLOCATE
content_buffer = why2_realloc(content_buffer, content_size + 1); content_buffer = why2_malloc(content_size + 1);
//READ JSON MESSAGE //READ JSON MESSAGE
if (recv(socket, content_buffer, content_size, 0) != content_size) //READ THE MESSAGE BY CHARACTERS if (recv(socket, content_buffer, content_size, MSG_PEEK) != content_size) //READ THE MESSAGE BY CHARACTERS
{ {
fprintf(stderr, "Socket probably read wrongly!\n"); fprintf(stderr, "Socket probably read wrongly!\n");
} }
why2_deallocate(content_buffer); //CLEANUP
} while (content_buffer == NULL || strncmp(content_buffer + (content_size - 2), "\"}", 2) != 0); } while (content_buffer == NULL || strncmp(content_buffer + (content_size - 2), "\"}", 2) != 0);
content_buffer[content_size] = '\0'; //NULL TERM //ACTUALLY READ
content_buffer = why2_calloc(content_size + 1, sizeof(char)); //ALLOCATE
int i;
for (i = 0; i < content_size; i++)
{
//READ
if (recv(socket, content_buffer + i, 1, 0) != 1) //READ BY CHARS
{
fprintf(stderr, "Socket probably read wrongly!\n");
}
//REMOVE NON-ASCII
if (!is_ascii(content_buffer[i])) i--; //(REWRITE THE CURRENT CHAR)
}
content_buffer[i] = '\0'; //NULL TERM
//VALIDATE JSON FORMAT //VALIDATE JSON FORMAT
struct json_object *json = json_tokener_parse(content_buffer); struct json_object *json = json_tokener_parse(content_buffer);
@ -389,23 +406,12 @@ void send_socket_deallocate(char *text, char *username, int socket) //SAME AS wh
why2_toml_read_free(username); why2_toml_read_free(username);
} }
void send_socket_code_deallocate(char *params, char *username, int socket, char *code) //SAME AS send_socket_deallocate BUT WITH CODE FIELD void send_socket(char *text, char *username, int socket, why2_bool welcome)
{ {
why2_send_socket_code(params, username, socket, code);
why2_toml_read_free(username);
}
void send_socket(char *text, char *username, int socket, why2_bool welcome, char *code)
{
//VARIABLES
char *output = why2_strdup(""); char *output = why2_strdup("");
struct json_object *json = json_tokener_parse("{}");
if (text != NULL)
{
size_t length_buffer = strlen(text); size_t length_buffer = strlen(text);
char *text_copy = why2_calloc(length_buffer + 2, sizeof(char)); char *text_copy = why2_calloc(length_buffer + 2, sizeof(char));
struct json_object *json = json_tokener_parse("{}");
//COPY text INTO text_copy (WITHOUT LAST CHARACTER WHEN NEWLINE IS AT THE END) //COPY text INTO text_copy (WITHOUT LAST CHARACTER WHEN NEWLINE IS AT THE END)
if (text[length_buffer - 1] == '\n') length_buffer--; if (text[length_buffer - 1] == '\n') length_buffer--;
@ -419,11 +425,6 @@ void send_socket(char *text, char *username, int socket, why2_bool welcome, char
//ADD OBJECTS //ADD OBJECTS
json_object_object_add(json, "message", json_object_new_string(text_copy)); json_object_object_add(json, "message", json_object_new_string(text_copy));
//DEALLOCATION
why2_deallocate(text_copy);
}
if (username != NULL) json_object_object_add(json, "username", json_object_new_string(username)); //WAS SENT FROM SERVER if (username != NULL) json_object_object_add(json, "username", json_object_new_string(username)); //WAS SENT FROM SERVER
if (welcome) //SENDING WELCOME MESSAGE TO USER if (welcome) //SENDING WELCOME MESSAGE TO USER
@ -447,8 +448,6 @@ void send_socket(char *text, char *username, int socket, why2_bool welcome, char
why2_toml_read_free(server_name); why2_toml_read_free(server_name);
} }
if (code != NULL) json_object_object_add(json, "code", json_object_new_string(code));
//GENERATE JSON STRING //GENERATE JSON STRING
json_object_object_foreach(json, key, value) json_object_object_foreach(json, key, value)
{ {
@ -456,17 +455,19 @@ void send_socket(char *text, char *username, int socket, why2_bool welcome, char
} }
add_brackets(&output); add_brackets(&output);
why2_deallocate(text_copy);
json_object_put(json);
//SEND //SEND
send(socket, output, strlen(output), 0); send(socket, output, strlen(output), 0);
//DEALLOCATION //DEALLOCATION
json_object_put(json);
why2_deallocate(output); why2_deallocate(output);
} }
void send_welcome_socket_deallocate(char *text, char *username, int socket) //SAME AS why2_send_socket BUT IT DEALLOCATES username void send_welcome_socket_deallocate(char *text, char *username, int socket) //SAME AS why2_send_socket BUT IT DEALLOCATES username
{ {
send_socket(NULL, username, socket, 1, text); send_socket(text, username, socket, 1);
why2_toml_read_free(username); why2_toml_read_free(username);
} }
@ -502,12 +503,7 @@ unsigned long get_latest_id()
//GLOBAL //GLOBAL
void why2_send_socket(char *text, char *username, int socket) void why2_send_socket(char *text, char *username, int socket)
{ {
send_socket(text, username, socket, 0, NULL); send_socket(text, username, socket, 0);
}
void why2_send_socket_code(char *params, char *username, int socket, char *code)
{
send_socket(params, username, socket, 0, code);
} }
void *why2_communicate_thread(void *arg) void *why2_communicate_thread(void *arg)
@ -528,7 +524,6 @@ void *why2_communicate_thread(void *arg)
why2_bool invalid_username = 1; why2_bool invalid_username = 1;
why2_bool exiting = 0; why2_bool exiting = 0;
char *decoded_buffer = NULL; char *decoded_buffer = NULL;
char *decoded_code_buffer = NULL;
char *username; char *username;
int usernames_n = 0; int usernames_n = 0;
struct json_object *json = json_tokener_parse("{}"); struct json_object *json = json_tokener_parse("{}");
@ -542,7 +537,7 @@ void *why2_communicate_thread(void *arg)
{ {
if (config_username == NULL) fprintf(stderr, "Your config doesn't contain 'user_pick_username'. Please update your configuration.\n"); if (config_username == NULL) fprintf(stderr, "Your config doesn't contain 'user_pick_username'. Please update your configuration.\n");
send_socket_code_deallocate(NULL, why2_chat_server_config("server_username"), connection, WHY2_CHAT_CODE_PICK_USERNAME); //ASK USER FOR USERNAME send_socket_deallocate(WHY2_CHAT_CODE_PICK_USERNAME, why2_chat_server_config("server_username"), connection); //ASK USER FOR USERNAME
while (invalid_username) while (invalid_username)
{ {
@ -591,63 +586,10 @@ void *why2_communicate_thread(void *arg)
if (invalid_username) if (invalid_username)
{ {
send_socket_code_deallocate(NULL, why2_chat_server_config("server_username"), connection, WHY2_CHAT_CODE_INVALID_USERNAME); //TELL THE USER THEY ARE DUMB AS FUCK send_socket_deallocate(WHY2_CHAT_CODE_INVALID_USERNAME, why2_chat_server_config("server_username"), connection); //TELL THE USER THEY ARE DUMB AS FUCK
continue; continue;
} }
//USER CONFIG
char *password = NULL;
char *user_config_path = why2_get_server_users_path();
if (!why2_toml_contains(user_config_path, decoded_buffer)) //REGISTRATION
{
send_socket_code_deallocate(NULL, why2_chat_server_config("server_username"), connection, WHY2_CHAT_CODE_ENTER_PASSWORD);
if ((raw = read_user(connection, &raw_ptr)) == NULL) //READ
{
force_exiting = 1; //FAILURE
goto deallocation;
}
password = get_string_from_json_string(raw, "message"); //DECODE
why2_toml_write(user_config_path, username, password); //SAVE PASSWORD
} else //LOGIN
{
send_socket_code_deallocate(NULL, why2_chat_server_config("server_username"), connection, WHY2_CHAT_CODE_ENTER_PASSWORD);
unsigned char max_tries = (unsigned char) server_config_int("max_password_tries");
for (unsigned char i = 0; i < max_tries; i++)
{
if ((raw = read_user(connection, &raw_ptr)) == NULL) //READ
{
force_exiting = 1; //FAILURE
goto deallocation;
}
password = get_string_from_json_string(raw, "message"); //DECODE
if (why2_toml_equals(user_config_path, decoded_buffer, password)) break;
if (i == max_tries - 1) //NOP, TOO MANY INVALID PASSWORDS
{
why2_deallocate(password);
exiting = 1;
goto deallocation;
}
send_socket_code_deallocate(NULL, why2_chat_server_config("server_username"), connection, WHY2_CHAT_CODE_INVALID_PASSWORD);
}
}
//CLEANUP
why2_deallocate(user_config_path);
why2_deallocate(password);
why2_deallocate(raw);
//INFO
printf("User set username.\t%d\t%s\n", connection, decoded_buffer); printf("User set username.\t%d\t%s\n", connection, decoded_buffer);
} }
} }
@ -659,8 +601,7 @@ void *why2_communicate_thread(void *arg)
connection, connection,
pthread_self(), pthread_self(),
why2_strdup(username), why2_strdup(username),
get_latest_id(), get_latest_id()
why2_generate_key(why2_get_key_length())
}; };
why2_list_push(&connection_list, &node, sizeof(node)); //ADD TO LIST why2_list_push(&connection_list, &node, sizeof(node)); //ADD TO LIST
@ -703,17 +644,18 @@ void *why2_communicate_thread(void *arg)
} }
decoded_buffer = get_string_from_json_string(raw, "message"); //DECODE decoded_buffer = get_string_from_json_string(raw, "message"); //DECODE
decoded_code_buffer = get_string_from_json_string(raw, "code"); //DECODE
//TRIM MESSAGE //TRIM MESSAGE
if (decoded_buffer != NULL) why2_trim_string(&decoded_buffer); why2_trim_string(&decoded_buffer);
if (decoded_code_buffer != NULL) //CODES FROM CLIENT if (decoded_buffer != NULL && strlen(decoded_buffer) != 0)
{ {
if (strcmp(decoded_code_buffer, WHY2_CHAT_CODE_EXIT) == 0) //USER REQUESTED EXIT if (strncmp(decoded_buffer, "code", 4) == 0) //CODES FROM CLIENT
{
if (strcmp(decoded_buffer, WHY2_CHAT_CODE_EXIT) == 0) //USER REQUESTED EXIT
{ {
exiting = 1; exiting = 1;
} else if (strcmp(decoded_code_buffer, WHY2_CHAT_CODE_LIST) == 0) //USER REQUESTED LIST OF USERS } else if (strcmp(decoded_buffer, WHY2_CHAT_CODE_LIST) == 0) //USER REQUESTED LIST OF USERS
{ {
why2_node_t *head = connection_list.head; why2_node_t *head = connection_list.head;
if (head == NULL) goto deallocation; //TODO: Send no users code if (head == NULL) goto deallocation; //TODO: Send no users code
@ -722,7 +664,7 @@ void *why2_communicate_thread(void *arg)
why2_node_t *buffer = head; why2_node_t *buffer = head;
connection_node_t value_buffer; connection_node_t value_buffer;
unsigned long alloc_size = 0; unsigned long alloc_size = 0;
size_t last_size = 0; char *append_buffer;
//COUNT REQUIRED MESSAGE ALLOCATION SIZE //COUNT REQUIRED MESSAGE ALLOCATION SIZE
do do
@ -733,51 +675,59 @@ void *why2_communicate_thread(void *arg)
buffer = buffer -> next; //ITER buffer = buffer -> next; //ITER
} while (buffer != NULL); } while (buffer != NULL);
char *message = why2_calloc(alloc_size + 1, sizeof(char)); char *message = why2_calloc(strlen(WHY2_CHAT_CODE_LIST_SERVER) + alloc_size + 2, sizeof(char));
buffer = head; //RESET buffer = head; //RESET
sprintf(message, WHY2_CHAT_CODE_LIST_SERVER); //SET CODE
//FILL THE message //FILL THE message
do do
{ {
value_buffer = *(connection_node_t*) buffer -> value; value_buffer = *(connection_node_t*) buffer -> value;
sprintf(message + last_size, "%s;%ld;", value_buffer.username, value_buffer.id); //APPEND append_buffer = why2_malloc(strlen(value_buffer.username) + why2_count_int_length(value_buffer.id) + 3); //ALLOCATE THE BUFFER
sprintf(append_buffer, ";%s;%ld", value_buffer.username, value_buffer.id); //FILL THE BUFFER
last_size = strlen(message); strcat(message, append_buffer); //JOIN THE BUFFER TO OUTPUT message
why2_deallocate(append_buffer); //DEALLOCATION
buffer = buffer -> next; //ITER buffer = buffer -> next; //ITER
} while (buffer != NULL); } while (buffer != NULL);
strcat(message, ";");
//SEND //SEND
send_socket_code_deallocate(message, why2_chat_server_config("server_username"), connection, WHY2_CHAT_CODE_LIST_SERVER); send_socket_deallocate(message, why2_chat_server_config("server_username"), connection);
//DEALLOCATION //DEALLOCATION
why2_deallocate(message); why2_deallocate(message);
} else if (strcmp(decoded_code_buffer, WHY2_CHAT_CODE_VERSION) == 0) } else if (strcmp(decoded_buffer, WHY2_CHAT_CODE_VERSION) == 0)
{ {
//GET VERSION STRING FROM THE VERSIONS JSON //GET VERSION STRING FROM THE VERSIONS JSON
char *message = why2_malloc(strlen(WHY2_VERSION) + 1); //ALLOCATE MESSAGE FOR CLIENT char *message = why2_malloc(strlen(WHY2_CHAT_CODE_VERSION_SERVER) + strlen(WHY2_VERSION) + 2); //ALLOCATE MESSAGE FOR CLIENT
sprintf(message, "%s%c", WHY2_VERSION, '\0'); //CREATE THE MESSAGE sprintf(message, WHY2_CHAT_CODE_VERSION_SERVER ";%s%c", WHY2_VERSION, '\0'); //CREATE THE MESSAGE
//SEND //SEND
send_socket_code_deallocate(message, why2_chat_server_config("server_username"), connection, WHY2_CHAT_CODE_VERSION_SERVER); send_socket_deallocate(message, why2_chat_server_config("server_username"), connection);
//DEALLOCATION //DEALLOCATION
why2_deallocate(message); why2_deallocate(message);
} else if (strcmp(decoded_code_buffer, WHY2_CHAT_CODE_PM) == 0 && decoded_buffer != NULL && strlen(decoded_buffer) != 0) //PM } else if (strncmp(decoded_buffer, WHY2_CHAT_CODE_PM, strlen(WHY2_CHAT_CODE_PM)) == 0) //PM
{ {
char *input = decoded_buffer + strlen(WHY2_CHAT_CODE_PM) + 1;
char *id = NULL; //RECEIVER char *id = NULL; //RECEIVER
char *msg; char *msg;
//CHECK ARGS VALIDITY //CHECK ARGS VALIDITY
why2_bool valid_param = strlen(decoded_buffer) >= 3; why2_bool valid_param = strlen(input) >= 3;
if (valid_param) if (valid_param)
{ {
valid_param = 0; valid_param = 0;
for (unsigned long i = 1; i < strlen(decoded_buffer); i++) for (unsigned long i = 1; i < strlen(input); i++)
{ {
if (decoded_buffer[i] == ';') if (input[i] == ';')
{ {
valid_param = 1; valid_param = 1;
@ -785,12 +735,12 @@ void *why2_communicate_thread(void *arg)
id = why2_malloc(i + 1); id = why2_malloc(i + 1);
for (unsigned long j = 0; j < i; j++) for (unsigned long j = 0; j < i; j++)
{ {
id[j] = decoded_buffer[j]; id[j] = input[j];
} }
id[i] = '\0'; id[i] = '\0';
//EXTRACT MESSAGE //EXTRACT MESSAGE
msg = decoded_buffer + i + 1; msg = input + i + 1;
break; break;
} }
} }
@ -805,17 +755,17 @@ void *why2_communicate_thread(void *arg)
connection_node_t pm_connection_node = *(connection_node_t*) pm_connection -> value; connection_node_t pm_connection_node = *(connection_node_t*) pm_connection -> value;
//ALLOCATE MESSAGE TO SEND TO RECEIVER //ALLOCATE MESSAGE TO SEND TO RECEIVER
char *private_msg = why2_malloc(strlen(node.username) + strlen(pm_connection_node.username) + strlen(msg) + 5); char *private_msg = why2_malloc(strlen(WHY2_CHAT_CODE_PM_SERVER) + strlen(node.username) + strlen(pm_connection_node.username) + strlen(msg) + 6);
//CONSTRUCT DA MESSAGE //CONSTRUCT DA MESSAGE
sprintf(private_msg, "%s;%s;%s;%c", node.username, pm_connection_node.username, msg, '\0'); sprintf(private_msg, WHY2_CHAT_CODE_PM_SERVER ";%s;%s;%s;%c", node.username, pm_connection_node.username, msg, '\0');
//USER IS SENDING THE MESSAGE TO HIMSELF //USER IS SENDING THE MESSAGE TO HIMSELF
why2_bool self_pm = pm_connection_node.connection == connection; why2_bool self_pm = pm_connection_node.connection == connection;
//SEND YOU DUMB FUCK //SEND YOU DUMB FUCK
send_socket_code_deallocate(private_msg, why2_chat_server_config("server_username"), pm_connection_node.connection, WHY2_CHAT_CODE_PM_SERVER); //RECIPIENT send_socket_deallocate(private_msg, why2_chat_server_config("server_username"), pm_connection_node.connection); //RECIPIENT
if (!self_pm) send_socket_code_deallocate(private_msg, why2_chat_server_config("server_username"), connection, WHY2_CHAT_CODE_PM_SERVER); //AUTHOR if (!self_pm) send_socket_deallocate(private_msg, why2_chat_server_config("server_username"), connection); //AUTHOR
why2_deallocate(private_msg); why2_deallocate(private_msg);
} }
@ -825,7 +775,7 @@ void *why2_communicate_thread(void *arg)
} }
//IGNORE INVALID CODES, THE USER JUST GOT THEIR LOBOTOMY DONE //IGNORE INVALID CODES, THE USER JUST GOT THEIR LOBOTOMY DONE
} else if (decoded_buffer != NULL && strlen(decoded_buffer) != 0 && strncmp(decoded_buffer, WHY2_CHAT_COMMAND_PREFIX, strlen(WHY2_CHAT_COMMAND_PREFIX)) != 0) //IGNORE MESSAGES BEGINNING WITH '!' } else if (strncmp(decoded_buffer, WHY2_CHAT_COMMAND_PREFIX, strlen(WHY2_CHAT_COMMAND_PREFIX)) != 0) //IGNORE MESSAGES BEGINNING WITH '!'
{ {
//REBUILD MESSAGE WITH USERNAME //REBUILD MESSAGE WITH USERNAME
json_object_object_add(json, "message", json_object_new_string(decoded_buffer)); json_object_object_add(json, "message", json_object_new_string(decoded_buffer));
@ -839,6 +789,7 @@ void *why2_communicate_thread(void *arg)
send_to_all(raw_output); //e send_to_all(raw_output); //e
} }
}
deallocation: deallocation:
@ -847,18 +798,16 @@ void *why2_communicate_thread(void *arg)
why2_deallocate(raw_ptr); why2_deallocate(raw_ptr);
why2_deallocate(raw_output); why2_deallocate(raw_output);
why2_deallocate(decoded_buffer); why2_deallocate(decoded_buffer);
why2_deallocate(decoded_code_buffer);
json_object_put(json); json_object_put(json);
} }
if (exiting) send_socket_code_deallocate(NULL, why2_chat_server_config("server_username"), connection, WHY2_CHAT_CODE_SSQC); if (exiting) send_socket_deallocate(WHY2_CHAT_CODE_SSQC, why2_chat_server_config("server_username"), connection);
printf("User disconnected.\t%d\n", connection); printf("User disconnected.\t%d\n", connection);
//DEALLOCATION //DEALLOCATION
close(connection); close(connection);
why2_deallocate(node.username); why2_deallocate(node.username);
why2_deallocate(node.key);
why2_list_remove(&connection_list, find_connection(connection)); why2_list_remove(&connection_list, find_connection(connection));
@ -899,7 +848,7 @@ void why2_clean_connections(void)
connection_buffer = *(connection_node_t*) node_buffer_2 -> value; connection_buffer = *(connection_node_t*) node_buffer_2 -> value;
send_socket_code_deallocate(NULL, why2_chat_server_config("server_username"), connection_buffer.connection, WHY2_CHAT_CODE_SSQC); send_socket_deallocate(WHY2_CHAT_CODE_SSQC, why2_chat_server_config("server_username"), connection_buffer.connection);
close(connection_buffer.connection); close(connection_buffer.connection);
why2_list_remove(&connection_list, node_buffer_2); //REMOVE why2_list_remove(&connection_list, node_buffer_2); //REMOVE
@ -931,13 +880,11 @@ void *why2_listen_server(void *socket)
why2_bool exiting = 0; why2_bool exiting = 0;
why2_bool continuing; why2_bool continuing;
unsigned char asking_username = 0; unsigned char asking_username = 0;
unsigned char asking_password = 0;
char *server_uname = NULL; char *server_uname = NULL;
//CONTENT //CONTENT
char *username = NULL; char *username = NULL;
char *message = NULL; char *message = NULL;
char *code = NULL;
//SERVER SETTINGS //SERVER SETTINGS
int max_uname = -1; int max_uname = -1;
@ -958,12 +905,9 @@ void *why2_listen_server(void *socket)
//GET CONTENT //GET CONTENT
username = get_string_from_json_string(read, "username"); username = get_string_from_json_string(read, "username");
message = get_string_from_json_string(read, "message"); message = get_string_from_json_string(read, "message");
code = get_string_from_json_string(read, "code");
if (server_uname == NULL) //GET SERVER USERNAME if (server_uname == NULL) //GET SERVER USERNAME
{ {
if (code == NULL || strcmp(code, WHY2_CHAT_CODE_ACCEPT_MESSAGES) != 0) goto deallocation;
server_uname = why2_strdup(username); //GET USERNAME server_uname = why2_strdup(username); //GET USERNAME
//GET INFO //GET INFO
@ -972,24 +916,24 @@ void *why2_listen_server(void *socket)
max_tries = get_int_from_json_string(read, "max_tries"); max_tries = get_int_from_json_string(read, "max_tries");
server_name = get_string_from_json_string(read, "server_name"); server_name = get_string_from_json_string(read, "server_name");
printf(WHY2_CLEAR_AND_GO_UP WHY2_CLEAR_AND_GO_UP "Successfully connected to %s.\nUse !help for commands.\n\n\n", server_name); //WELCOME printf(WHY2_CLEAR_AND_GO_UP WHY2_CLEAR_AND_GO_UP "Successfully connected to %s.\n\n\n", server_name); //WELCOME
why2_deallocate(server_name); why2_deallocate(server_name);
continuing = 1; continuing = 1;
} }
if ((strcmp(username, server_uname) == 0 && code != NULL) && !continuing) //CODE WAS SENT if ((strcmp(username, server_uname) == 0 && strncmp(message, "code", 4) == 0) && !continuing) //CODE WAS SENT
{ {
if (strcmp(code, WHY2_CHAT_CODE_SSQC) == 0) //SERVER BROKE UP WITH YOU if (strcmp(message, WHY2_CHAT_CODE_SSQC) == 0) //SERVER BROKE UP WITH YOU
{ {
printf("%s%s%s\nServer closed the connection.\n", asking_username > max_tries ? WHY2_CLEAR_AND_GO_UP : "", WHY2_CLEAR_AND_GO_UP WHY2_CLEAR_AND_GO_UP, (asking_username == 0 ? "\n": "")); printf("%s%s%s\nServer closed the connection.\n", asking_username > max_tries ? WHY2_CLEAR_AND_GO_UP : "", WHY2_CLEAR_AND_GO_UP WHY2_CLEAR_AND_GO_UP, (asking_username == 0 ? "\n": ""));
fflush(stdout); fflush(stdout);
pthread_cancel(getline_thread); //CANCEL CLIENT getline pthread_cancel(getline_thread); //CANCEL CLIENT getline
exiting = 1; //EXIT THIS THREAD exiting = 1; //EXIT THIS THREAD
} else if (strcmp(code, WHY2_CHAT_CODE_PICK_USERNAME) == 0 || strcmp(code, WHY2_CHAT_CODE_INVALID_USERNAME) == 0) //PICK USERNAME (COULD BE CAUSE BY INVALID USERNAME) } else if (strcmp(message, WHY2_CHAT_CODE_PICK_USERNAME) == 0 || strcmp(message, WHY2_CHAT_CODE_INVALID_USERNAME) == 0) //PICK USERNAME (COULD BE CAUSE BY INVALID USERNAME)
{ {
if (strcmp(code, WHY2_CHAT_CODE_INVALID_USERNAME) == 0) //INVALID USERNAME if (strcmp(message, WHY2_CHAT_CODE_INVALID_USERNAME) == 0) //INVALID USERNAME
{ {
printf(WHY2_CLEAR_AND_GO_UP WHY2_CLEAR_AND_GO_UP "%s\nInvalid username!\n\n\n", asking_username > 1 ? WHY2_CLEAR_AND_GO_UP : ""); printf(WHY2_CLEAR_AND_GO_UP WHY2_CLEAR_AND_GO_UP "%s\nInvalid username!\n\n\n", asking_username > 1 ? WHY2_CLEAR_AND_GO_UP : "");
fflush(stdout); fflush(stdout);
@ -997,14 +941,14 @@ void *why2_listen_server(void *socket)
printf("%s%sEnter username (a-Z, 0-9; %d-%d characters):\n", asking_username++ > 0 ? WHY2_CLEAR_AND_GO_UP : "", WHY2_CLEAR_AND_GO_UP, min_uname, max_uname); printf("%s%sEnter username (a-Z, 0-9; %d-%d characters):\n", asking_username++ > 0 ? WHY2_CLEAR_AND_GO_UP : "", WHY2_CLEAR_AND_GO_UP, min_uname, max_uname);
fflush(stdout); fflush(stdout);
} else if (strcmp(code, WHY2_CHAT_CODE_LIST_SERVER) == 0) //LIST USERS } else if (strncmp(message, WHY2_CHAT_CODE_LIST_SERVER, strlen(WHY2_CHAT_CODE_LIST_SERVER)) == 0) //LIST USERS
{ {
why2_bool printing_id = 0; why2_bool printing_id = 0;
printf("\nList:\n-----\n"); printf("\nList:\n-----\n");
//ITER TROUGH LIST OF USERS FROM SERVER //ITER TROUGH LIST OF USERS FROM SERVER
for (unsigned long i = 0; i < strlen(message); i++) for (unsigned long i = strlen(WHY2_CHAT_CODE_LIST_SERVER) + 1; i < strlen(message); i++)
{ {
if (message[i] == ';') if (message[i] == ';')
{ {
@ -1017,20 +961,24 @@ void *why2_listen_server(void *socket)
printf("\n"); printf("\n");
fflush(stdout); fflush(stdout);
} else if (strcmp(code, WHY2_CHAT_CODE_VERSION_SERVER) == 0) } else if (strncmp(message, WHY2_CHAT_CODE_VERSION_SERVER, strlen(WHY2_CHAT_CODE_VERSION_SERVER)) == 0)
{ {
char *server_version = message + strlen(WHY2_CHAT_CODE_VERSION_SERVER) + 1;
//INFO //INFO
printf("\nServer Version: %s\nClient Version: %s\n\n", message, WHY2_VERSION); printf("\nServer Version: %s\nClient Version: %s\n\n", server_version, WHY2_VERSION);
//SERVER IS OUTDATED //SERVER IS OUTDATED
if (atoi(message + 1) < atoi(WHY2_VERSION + 1)) if (atoi(server_version + 1) < atoi(WHY2_VERSION + 1))
{ {
printf("Server is outdated. Some new features may not work correctly.\n\n"); printf("Server is outdated. Some new features may not work correctly.\n\n");
} }
} else if (strcmp(code, WHY2_CHAT_CODE_PM_SERVER) == 0) } else if (strncmp(message, WHY2_CHAT_CODE_PM_SERVER, strlen(WHY2_CHAT_CODE_PM_SERVER)) == 0)
{ {
printf(WHY2_CLEAR_AND_GO_UP WHY2_CLEAR_AND_GO_UP); //do not fucking ask me how the fucking formatting fucking works, i dont fucking know printf(WHY2_CLEAR_AND_GO_UP WHY2_CLEAR_AND_GO_UP); //do not fucking ask me how the fucking formatting fucking works, i dont fucking know
char *received_pm = message + strlen(WHY2_CHAT_CODE_PM_SERVER) + 1;
//DECODED MESSAGE, AUTHOR AND RECIPIENT; 0 = AUTHOR, 1 = RECIPIENT, 2 = MESSAGE //DECODED MESSAGE, AUTHOR AND RECIPIENT; 0 = AUTHOR, 1 = RECIPIENT, 2 = MESSAGE
char **pm_info = why2_calloc(3, sizeof(char*)); char **pm_info = why2_calloc(3, sizeof(char*));
@ -1038,9 +986,9 @@ void *why2_listen_server(void *socket)
unsigned long n_buffer = 0; unsigned long n_buffer = 0;
//DECODE //DECODE
for (unsigned long i = 0; i < strlen(message); i++) for (unsigned long i = 0; i < strlen(received_pm); i++)
{ {
if (message[i] == ';') //FUTURE ME, THIS IS PRETTY MUCH split FUNCTION IMPLEMENTATION if (received_pm[i] == ';') //FUTURE ME, THIS IS PRETTY MUCH split FUNCTION IMPLEMENTATION
{ {
//ALLOCATE INFO //ALLOCATE INFO
pm_info[n_buffer] = why2_malloc((i - i_buffer) + 1); pm_info[n_buffer] = why2_malloc((i - i_buffer) + 1);
@ -1048,7 +996,7 @@ void *why2_listen_server(void *socket)
//COPY INFO //COPY INFO
for (unsigned long j = i_buffer; j < i; j++) for (unsigned long j = i_buffer; j < i; j++)
{ {
pm_info[n_buffer][j - i_buffer] = message[j]; pm_info[n_buffer][j - i_buffer] = received_pm[j];
} }
pm_info[n_buffer][i - i_buffer] = '\0'; pm_info[n_buffer][i - i_buffer] = '\0';
@ -1072,19 +1020,6 @@ void *why2_listen_server(void *socket)
why2_deallocate(pm_info[i]); why2_deallocate(pm_info[i]);
} }
why2_deallocate(pm_info); why2_deallocate(pm_info);
} else if (strcmp(code, WHY2_CHAT_CODE_ENTER_PASSWORD) == 0 || strcmp(code, WHY2_CHAT_CODE_INVALID_PASSWORD) == 0) //PICK USERNAME (COULD BE CAUSE BY INVALID USERNAME)
{
__why2_set_asking_password(1);
if (strcmp(code, WHY2_CHAT_CODE_INVALID_PASSWORD) == 0) //INVALID USERNAME
{
printf(WHY2_CLEAR_AND_GO_UP WHY2_CLEAR_AND_GO_UP "%s\nInvalid password!\n\n\n", asking_password > 1 ? WHY2_CLEAR_AND_GO_UP : "");
fflush(stdout);
}
printf("%s%s\nEnter password:\n", asking_password++ > 0 ? WHY2_CLEAR_AND_GO_UP : "", WHY2_CLEAR_AND_GO_UP WHY2_CLEAR_AND_GO_UP);
fflush(stdout);
//TODO! THIS SOMEHOW BREAKS THE CLIENT INPUT
} }
} else if (!continuing) } else if (!continuing)
{ {
@ -1099,19 +1034,17 @@ void *why2_listen_server(void *socket)
printf("\n\n%s%s: %s\n\n", WHY2_CLEAR_AND_GO_UP, username, message); printf("\n\n%s%s: %s\n\n", WHY2_CLEAR_AND_GO_UP, username, message);
} }
if (!exiting && !continuing) if (!exiting && !continuing)
{ {
printf(">>> "); printf(">>> ");
fflush(stdout); fflush(stdout);
} }
deallocation:
//DEALLOCATION //DEALLOCATION
why2_deallocate(read); why2_deallocate(read);
why2_deallocate(username); why2_deallocate(username);
why2_deallocate(message); why2_deallocate(message);
why2_deallocate(code);
} }
why2_deallocate(server_uname); why2_deallocate(server_uname);

View File

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

View File

@ -23,13 +23,11 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <stdlib.h> #include <stdlib.h>
#include <sys/time.h> #include <sys/time.h>
#include <why2/crypto.h>
#include <why2/flags.h> #include <why2/flags.h>
#include <why2/llist.h>
#include <why2/memory.h> #include <why2/memory.h>
#include <why2/misc.h> #include <why2/misc.h>
why2_output_flags why2_decrypt_text(char *text, char *key) why2_output_flags why2_decrypt_text(char *text, char *key_new)
{ {
//CHECK VARIABLE //CHECK VARIABLE
unsigned char check_exit_code; unsigned char check_exit_code;
@ -52,13 +50,13 @@ why2_output_flags why2_decrypt_text(char *text, char *key)
} }
//CHECK FOR INVALID key //CHECK FOR INVALID key
if ((check_exit_code = why2_check_key(key)) != WHY2_SUCCESS) if ((check_exit_code = why2_check_key(key_new)) != WHY2_SUCCESS)
{ {
return why2_no_output(check_exit_code); return why2_no_output(check_exit_code);
} }
//REDEFINE keyLength //REDEFINE keyLength
why2_set_key_length(strlen(key)); why2_set_key_length(strlen(key_new));
//VARIABLES //VARIABLES
char *returning_text; char *returning_text;
@ -67,7 +65,7 @@ why2_output_flags why2_decrypt_text(char *text, char *key)
char *text_buffer = NULL; char *text_buffer = NULL;
int text_key_chainLength; int text_key_chainLength;
int *text_key_chain; int *text_key_chain;
char *key_new = why2_strdup(key); //COPY key TO key_new char *key = why2_strdup(key_new); //COPY key_new TO key
int *encrypted_text_key_chain; int *encrypted_text_key_chain;
char *used_text = NULL; //COPY text TO used_text char *used_text = NULL; //COPY text TO used_text
@ -80,6 +78,12 @@ why2_output_flags why2_decrypt_text(char *text, char *key)
//GET ENCRYPTED NUMBERS //GET ENCRYPTED NUMBERS
for (unsigned short i = 0; i < why2_byte_format_length(text_copy); i++) 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 //PUT TOGETHER
encrypted_input[i] = (text_copy[3 + (i * 2)] << 7) | text_copy[2 + (i * 2)]; encrypted_input[i] = (text_copy[3 + (i * 2)] << 7) | text_copy[2 + (i * 2)];
@ -128,7 +132,7 @@ why2_output_flags why2_decrypt_text(char *text, char *key)
text_key_chainLength = number_buffer; text_key_chainLength = number_buffer;
//LOAD text_key_chain //LOAD text_key_chain
why2_generate_text_key_chain(key_new, text_key_chain, number_buffer); why2_generate_text_key_chain(key, text_key_chain, number_buffer);
//LOAD encrypted_text_key_chain //LOAD encrypted_text_key_chain
for (int i = 0; i < text_key_chainLength; i++) for (int i = 0; i < text_key_chainLength; i++)
@ -177,59 +181,6 @@ why2_output_flags why2_decrypt_text(char *text, char *key)
returning_text[i] = text_key_chain[i]; returning_text[i] = text_key_chain[i];
} }
//REMOVE PADDING
if (why2_get_flags().padding > 0)
{
why2_list_t split_text = WHY2_LIST_EMPTY; //LIST OF returning_text SPLIT INTO CHARS
//ADD CHARS
for (unsigned long i = 0; i < strlen(returning_text); i++)
{
why2_list_push(&split_text, &(returning_text[i]), sizeof(returning_text[i])); //ADD
}
//OBTAIN SEED FROM key_new
why2_seed_random(why2_sum_segment(key_new));
//GET RANDOM SEQUENCE USED IN ENCRYPTION
why2_list_t random_sequence = WHY2_LIST_EMPTY;
for (unsigned long i = 0; i < why2_get_flags().padding; i++)
{
int rand_buffer = why2_seeded_random();
why2_list_push(&random_sequence, &rand_buffer, sizeof(int)); //ADD
}
why2_list_reverse(&random_sequence, sizeof(int)); //REVERSE
//REMOVE PADDING FROM split_text LIST
for (unsigned long i = 0; i < why2_get_flags().padding; i++)
{
unsigned long random_position = (unsigned long) (*(int*) random_sequence.head -> value % (why2_list_get_size(&split_text) - 1)); //GET RANDOM POSITION
//REMOVE FROM THE LIST
why2_list_remove_at(&split_text, random_position);
//DEALLOCATION
why2_list_remove_at(&random_sequence, 0);
}
//PUT PADDED TEXT INTO text_new
returning_text = why2_recalloc(returning_text, why2_list_get_size(&split_text) + 1, sizeof(char));
why2_node_t *buffer = split_text.head;
why2_node_t *buffer_2;
unsigned long index_buffer = 0;
do
{
returning_text[index_buffer++] = *(char*) buffer -> value; //COPY VALUE
buffer_2 = buffer;
buffer = buffer -> next; //ITER
why2_deallocate(buffer_2 -> value); //DEALLOCATION
why2_deallocate(buffer_2); //DEALLOCATION
} while (buffer != NULL);
}
//GET FINISH TIME //GET FINISH TIME
gettimeofday(&finish_time, NULL); gettimeofday(&finish_time, NULL);
@ -237,9 +188,9 @@ why2_output_flags why2_decrypt_text(char *text, char *key)
why2_output_flags output = why2_output_flags output =
{ {
returning_text, //DECRYPTED TEXT returning_text, //DECRYPTED TEXT
key_new, //USED KEY key, //USED KEY
why2_count_unused_key_size(returning_text, key_new), // NUMBER OF WHY2_UNUSED CHARS IN KEY why2_count_unused_key_size(returning_text, key), // NUMBER OF WHY2_UNUSED CHARS IN KEY
why2_count_repeated_key_size(returning_text, key_new), //NUMBER OF REPEATED 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_compare_time_micro(start_time, finish_time), // ELAPSED TIME
WHY2_SUCCESS //EXIT CODE WHY2_SUCCESS //EXIT CODE
}; };

View File

@ -19,18 +19,14 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <why2/encrypter.h> #include <why2/encrypter.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h>
#include <string.h> #include <string.h>
#include <sys/time.h> #include <sys/time.h>
#include <limits.h>
#include <why2/crypto.h>
#include <why2/flags.h> #include <why2/flags.h>
#include <why2/llist.h>
#include <why2/memory.h> #include <why2/memory.h>
#include <why2/misc.h> #include <why2/misc.h>
why2_output_flags why2_encrypt_text(char *text, char *key) why2_output_flags why2_encrypt_text(char *text, char *key_new)
{ {
//CHECK VARIABLE //CHECK VARIABLE
unsigned char check_exit_code; unsigned char check_exit_code;
@ -55,104 +51,53 @@ why2_output_flags why2_encrypt_text(char *text, char *key)
why2_set_memory_identifier("core_decrypt"); why2_set_memory_identifier("core_decrypt");
//VARIABLES //VARIABLES
char *key_new = NULL; char *key = NULL;
char *text_new = NULL;
char *returning_text = NULL; char *returning_text = NULL;
char *text_buffer = NULL; char *text_buffer = NULL;
int *text_key_chain; int *text_key_chain = why2_malloc(sizeof(int) * strlen(text));
int number_buffer = 0; int number_buffer = 0;
if (key != NULL) if (key_new != NULL)
{ {
//CHECK FOR INVALID key_new //CHECK FOR INVALID key
if ((check_exit_code = why2_check_key(key)) != WHY2_SUCCESS) if ((check_exit_code = why2_check_key(key_new)) != WHY2_SUCCESS)
{ {
why2_clean_memory("core_decrypt"); why2_clean_memory("core_decrypt");
return why2_no_output(check_exit_code); return why2_no_output(check_exit_code);
} }
key_new = why2_strdup(key); key = why2_strdup(key_new);
//REDEFINE keyLength //REDEFINE keyLength
why2_set_key_length(strlen(key_new)); why2_set_key_length(strlen(key));
} else //LOAD KEY } else //LOAD KEY
{ {
key_new = why2_generate_key(why2_get_key_length()); key = why2_generate_key(why2_get_key_length());
} }
//PADDING
if (why2_get_flags().padding > 0)
{
why2_list_t split_text = WHY2_LIST_EMPTY; //LIST OF text SPLIT INTO CHARS
//ADD CHARS
for (unsigned long i = 0; i < strlen(text); i++)
{
why2_list_push(&split_text, &(text[i]), sizeof(text[i])); //ADD
}
//OBTAIN SEED FROM key_new
why2_seed_random(why2_sum_segment(key_new));
//ADD PADDING TO split_text LIST
for (unsigned long i = 0; i < why2_get_flags().padding; i++)
{
unsigned long random_position = (unsigned long) (why2_seeded_random() % (why2_list_get_size(&split_text))); //GET RANDOM POSITION
char random_char = 0;
for (int j = 0; j < WHY2_PADDING_NONZERO_TRIES && random_char == 0 ; j++) //GET RANDOM (EXCLUDING 0)
{
why2_random(&random_char, sizeof(random_char)); //GENERATE COMPLETELY RANDOM CHARACTER
}
if (random_char == 0) random_char = 1;
//INSERT RANDOM VALUE
why2_list_push_at(&split_text, random_position, &random_char, sizeof(random_char));
}
//PUT PADDED TEXT INTO text_new
text_new = why2_calloc(why2_list_get_size(&split_text) + 1, sizeof(char));
why2_node_t *buffer = split_text.head;
why2_node_t *buffer_2;
unsigned long index_buffer = 0;
do
{
text_new[index_buffer++] = *(char*) buffer -> value; //COPY VALUE
buffer_2 = buffer;
buffer = buffer -> next; //ITER
why2_deallocate(buffer_2 -> value); //DEALLOCATION
why2_deallocate(buffer_2); //DEALLOCATION
} while (buffer != NULL);
} else text_new = why2_strdup(text); //USE TEXT WITHOUT PADDING
text_key_chain = why2_malloc(sizeof(int) * strlen(text_new));
//LOAD text_key_chain //LOAD text_key_chain
why2_generate_text_key_chain(key_new, text_key_chain, strlen(text_new)); why2_generate_text_key_chain(key, text_key_chain, strlen(text));
//ACTUALLY ENCRYPT TEXT //ACTUALLY ENCRYPT TEXT
for (int i = 0; i < (int) strlen(text_new); i++) for (int i = 0; i < (int) strlen(text); i++)
{ {
text_key_chain[i] = why2_get_encryption_operation()(text_key_chain[i], (int) text_new[i]); text_key_chain[i] = why2_get_encryption_operation()(text_key_chain[i], (int) text[i]);
} }
//OUTPUT FORMATS //OUTPUT FORMATS
if (why2_get_flags().format == WHY2_OUTPUT_TEXT) //NORMAL 420.-69 FORMAT if (why2_get_flags().format == WHY2_OUTPUT_TEXT) //NORMAL 420.-69 FORMAT
{ {
//COUNT REQUIRED SIZE FOR returning_text //COUNT REQUIRED SIZE FOR returning_text
for (int i = 0; i < (int) strlen(text_new); i++) for (int i = 0; i < (int) strlen(text); i++)
{ {
number_buffer += why2_count_int_length(text_key_chain[i]); number_buffer += why2_count_int_length(text_key_chain[i]);
} }
//ALLOCATE returning_text (WITH THE SEPARATORS) //ALLOCATE returning_text (WITH THE SEPARATORS)
returning_text = why2_calloc(number_buffer + strlen(text_new), sizeof(char)); returning_text = why2_calloc(number_buffer + strlen(text), sizeof(char));
//LOAD returning_text //LOAD returning_text
for (int i = 0; i < (int) strlen(text_new); i++) for (int i = 0; i < (int) strlen(text); i++)
{ {
number_buffer = sizeof(int) * why2_count_int_length(text_key_chain[i]); number_buffer = sizeof(int) * why2_count_int_length(text_key_chain[i]);
@ -162,23 +107,23 @@ why2_output_flags why2_encrypt_text(char *text, char *key)
strcat(returning_text, text_buffer); strcat(returning_text, text_buffer);
if (i != (int) strlen(text_new) - 1) if (i != (int) strlen(text) - 1)
{ {
returning_text[strlen(returning_text)] = why2_get_encryption_separator(); returning_text[strlen(returning_text)] = why2_get_encryption_separator();
} }
} }
} else if (why2_get_flags().format == WHY2_OUTPUT_BYTE) //FUCKED BUT SHORT(ER) OUTPUT } else if (why2_get_flags().format == WHY2_OUTPUT_BYTE) //FUCKED BUT SHORT(ER) OUTPUT
{ {
number_buffer = (strlen(text_new) + 1) * 2; //EACH CHARACTER WILL BE SPLIT INTO TWO CHARS AND FIRST TWO WILL BE LENGTH OF text_new 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 returning_text = why2_calloc(number_buffer + 1, sizeof(char)); //ALLOCATE
//SET LENGTH //SET LENGTH
returning_text[0] = (strlen(text_new) & 0x7f) + 1; //+1 BECAUSE WE DON'T WANT \0 returning_text[0] = (strlen(text) & 0x7f) + 1; //+1 BECAUSE WE DON'T WANT \0
returning_text[1] = (strlen(text_new) >> 7) + 1; returning_text[1] = (strlen(text) >> 7) + 1;
//PUT THE text_key_chain INTO returning_text DIRECTLY //PUT THE text_key_chain INTO returning_text DIRECTLY
for (unsigned long i = 0; i < strlen(text_new); i++) for (unsigned long i = 0; i < strlen(text); i++)
{ {
//BUILD returning_text //BUILD returning_text
returning_text[2 + (i * 2)] = text_key_chain[i] & 0x7f; returning_text[2 + (i * 2)] = text_key_chain[i] & 0x7f;
@ -199,9 +144,9 @@ why2_output_flags why2_encrypt_text(char *text, char *key)
why2_output_flags output = why2_output_flags output =
{ {
returning_text, //ENCRYPTED TEXT returning_text, //ENCRYPTED TEXT
key_new, //GENERATED/USED KEY key, //GENERATED/USED KEY
why2_count_unused_key_size(text_new, key_new), // NUMBER OF WHY2_UNUSED CHARS IN KEY why2_count_unused_key_size(text, key), // NUMBER OF WHY2_UNUSED CHARS IN KEY
why2_count_repeated_key_size(text_new, key_new), //NUMBER OF REPEATED CHARS IN KEY why2_count_repeated_key_size(text, key), //NUMBER OF REPEATED CHARS IN KEY
why2_compare_time_micro(start_time, finish_time), // ELAPSED TIME why2_compare_time_micro(start_time, finish_time), // ELAPSED TIME
WHY2_SUCCESS //EXIT CODE WHY2_SUCCESS //EXIT CODE
}; };
@ -209,7 +154,6 @@ why2_output_flags why2_encrypt_text(char *text, char *key)
//DEALLOCATION //DEALLOCATION
why2_deallocate(text_key_chain); why2_deallocate(text_key_chain);
why2_deallocate(text_buffer); why2_deallocate(text_buffer);
why2_deallocate(text_new);
why2_reset_memory_identifier(); why2_reset_memory_identifier();

View File

@ -25,7 +25,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <why2/memory.h> #include <why2/memory.h>
//CONSTS (this is just local) //CONSTS (this is just local)
#define DEFAULT_FLAGS (why2_input_flags) { 0, 0, 0, WHY2_v4, WHY2_OUTPUT_TEXT, 64 } #define DEFAULT_FLAGS (why2_input_flags) { 0, 0, 0, WHY2_v3, WHY2_OUTPUT_TEXT }
#define DEFAULT_MEMORY_IDENTIFIER "" #define DEFAULT_MEMORY_IDENTIFIER ""
int encryptionOperation(int text, int encryptedText); int encryptionOperation(int text, int encryptedText);
@ -33,10 +33,9 @@ int encryptionOperation(int text, int encryptedText);
//VARIABLES //VARIABLES
char encryption_separator = '.'; //NOPE > DO NOT TOUCH THIS, USE why2_set_encryption_separator instead < 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 < unsigned long keyLength = 50; //LENGTH OF KEY > DO NOT TOUCH THIS, USE why2_set_key_length instead <
why2_input_flags used_flags = DEFAULT_FLAGS; //IT IS CALLED used_flags CUZ flags CAUSED SOME FUCKING MEMORY PROBLEMS 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_encryption_operation_cb encryptionOperation_cb = encryptionOperation;
why2_bool flags_changed = 0; //CHANGES TO 1 WHEN U USE why2_set_flags why2_bool flagsChanged = 0; //CHANGES TO 1 WHEN U USE why2_set_flags
why2_bool padding_changed = 0; //SAME AS flags_changed BUT FOR PADDING
char *memory_identifier = DEFAULT_MEMORY_IDENTIFIER; char *memory_identifier = DEFAULT_MEMORY_IDENTIFIER;
why2_list_t identifier_list = WHY2_LIST_EMPTY; why2_list_t identifier_list = WHY2_LIST_EMPTY;
@ -69,7 +68,7 @@ why2_input_flags why2_get_default_flags(void)
why2_input_flags why2_get_flags(void) why2_input_flags why2_get_flags(void)
{ {
return used_flags; return flagsAllah;
} }
why2_output_flags why2_no_output(enum WHY2_EXIT_CODES exit_code) why2_output_flags why2_no_output(enum WHY2_EXIT_CODES exit_code)
@ -94,12 +93,7 @@ why2_encryption_operation_cb why2_get_encryption_operation(void)
why2_bool why2_get_flags_changed(void) why2_bool why2_get_flags_changed(void)
{ {
return flags_changed; return flagsChanged;
}
why2_bool why2_get_padding_changed(void)
{
return padding_changed;
} }
char *why2_get_memory_identifier(void) char *why2_get_memory_identifier(void)
@ -132,20 +126,11 @@ void why2_set_key_length(int keyLengthNew)
keyLength = keyLengthNew; keyLength = keyLengthNew;
} }
void why2_set_flags(why2_input_flags new_flags) void why2_set_flags(why2_input_flags newFlags)
{ {
__why2_set_flags_anon(new_flags); flagsAllah = newFlags;
if (!flags_changed) if (!flagsChanged) flagsChanged = 1;
{
flags_changed = 1;
padding_changed = 1;
}
}
void __why2_set_flags_anon(why2_input_flags new_flags)
{
used_flags = new_flags;
} }
void why2_set_encryption_operation(why2_encryption_operation_cb newEncryptionOperation) void why2_set_encryption_operation(why2_encryption_operation_cb newEncryptionOperation)
@ -160,17 +145,6 @@ void why2_set_memory_identifier(char *new_memory_identifier)
memory_identifier = new_memory_identifier; memory_identifier = new_memory_identifier;
} }
void why2_set_padding(unsigned long padding)
{
__why2_set_padding_anon(padding);
if (!padding_changed) padding_changed = 1;
}
void __why2_set_padding_anon(unsigned long padding)
{
used_flags.padding = padding;
}
void why2_reset_memory_identifier(void) void why2_reset_memory_identifier(void)
{ {
why2_list_remove_back(&identifier_list); why2_list_remove_back(&identifier_list);

View File

@ -44,9 +44,8 @@ int main(void)
0, //SKIP CHECK 0, //SKIP CHECK
0, //NO OUTPUT 0, //NO OUTPUT
0, //UPDATE 0, //UPDATE
WHY2_v4, //LATEST VERSION WHY2_v3, //LATEST VERSION
WHY2_OUTPUT_TEXT, //READABLE TEXT OUTPUT WHY2_OUTPUT_TEXT //READABLE TEXT OUTPUT
WHY2_RECOMMENDED_PADDING_RATE(strlen(WHY2_TEST_TEXT)) //PADDING RATE
}; };
//SET FLAGS //SET FLAGS

View File

@ -1,101 +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/crypto.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <sys/types.h>
#include <sys/random.h>
#include <openssl/rand.h>
#include <openssl/hmac.h>
#include <why2/flags.h>
typedef struct
{
unsigned long seed; //DA SEED
unsigned long counter; //COUNTER FOR DETERMINISTIC OUTPUT
} PRNG_CTX; //GENERATOR
//LOCAL
PRNG_CTX generator = { 0, 0 }; //SEEDED RANDOM GENERATOR
//GLOBAL
unsigned long long why2_sum_segment(char *input) //THE OUTPUT IS GOING TO GROW A LOT WITH LONG input, BUT IT SHOULDN'T BE A BIG PROBLEM. I TESTED FOR OVERFLOWS UP TO 4096-CHAR input AND ONLY GOT TO (14*10^(-7))% OF FULL ULL RANGE LMAO
{
unsigned long input_size = strlen(input);
unsigned long segmented_input_size = ceil(input_size / (double) WHY2_SUM_SEGMENT_SIZE) * WHY2_SUM_SEGMENT_SIZE; //CALCULATE CLOSEST 32*n (OR WHY2_SUM_SEGMENT_SIZE*n, IF YOU WILL) TO input
unsigned long long output = 0;
for (unsigned long i = 0; i < segmented_input_size / WHY2_SUM_SEGMENT_SIZE; i++) //DIVIDE buffer INTO SEGMENTS, XOR EACH OTHER AND ADD TO output
{
unsigned long output_buffer = 0;
for (unsigned long j = 0; j < WHY2_SUM_SEGMENT_SIZE; j++)
{
unsigned long index_buffer = i * WHY2_SUM_SEGMENT_SIZE + j;
char value_buffer = (input_size > index_buffer) ? input[index_buffer] : 0;
output_buffer ^= value_buffer; //XORING
output_buffer = (output_buffer * WHY2_SUM_BASE_PRIME + value_buffer) % WHY2_SUM_MOD_PRIME;
}
output += output_buffer; //ADD
}
return output;
}
why2_bool why2_random(void *dest, size_t size)
{
return RAND_bytes((unsigned char*) dest, size) == 1;
}
void why2_seed_random(unsigned long seed)
{
memset(&generator, 0, sizeof(PRNG_CTX)); //INIT GENERATOR
memcpy(&(generator.seed), &seed, sizeof(generator.seed)); //COPY SEED
generator.counter = 0; //INIT COUNTER
}
int why2_seeded_random()
{
int output;
unsigned char counter_bytes[4];
unsigned char hmac_output[EVP_MAX_MD_SIZE];
unsigned int hmac_len;
//CONVERT COUNTER TO BYTES
counter_bytes[0] = (generator.counter >> 24) & 0xFF;
counter_bytes[1] = (generator.counter >> 16) & 0xFF;
counter_bytes[2] = (generator.counter >> 8) & 0xFF;
counter_bytes[3] = generator.counter & 0xFF;
//HMAC (seed || counter)
HMAC(EVP_sha256(), &(generator.seed), sizeof(generator.seed), counter_bytes, sizeof(counter_bytes), hmac_output, &hmac_len);
//USE THE FIRST 4 BYTES OF THE HMAC OUTPUT AS DETERMINISTIC RANDOM INTEGER
memcpy(&output, hmac_output, sizeof(output));
//INCREMENT COUNTER
generator.counter++;
return output;
}

View File

@ -22,14 +22,12 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <why2/memory.h>
void why2_list_push(why2_list_t *list, void *value, unsigned long size) void why2_list_push(why2_list_t *list, void *value, unsigned long size)
{ {
//CREATE NODE //CREATE NODE
why2_node_t *head = list -> head; why2_node_t *head = list -> head;
why2_node_t *new_node = why2_malloc(sizeof(why2_node_t)); why2_node_t *new_node = malloc(sizeof(why2_node_t));
new_node -> value = why2_malloc(size); new_node -> value = malloc(size);
why2_node_t *buffer = head; why2_node_t *buffer = head;
//INSERT DATA //INSERT DATA
@ -53,31 +51,6 @@ void why2_list_push(why2_list_t *list, void *value, unsigned long size)
list -> head = buffer; list -> head = buffer;
} }
void why2_list_push_at(why2_list_t *list, unsigned long index, void *value, unsigned long size)
{
//CREATE NODE
why2_node_t *head = list -> head;
why2_node_t *new_node = why2_malloc(sizeof(why2_node_t));
new_node -> value = why2_malloc(size);
//INSERT DATA
memcpy(new_node -> value, value, size);
if (index != 0 && head != NULL) //ISN'T FIRST
{
why2_node_t *node_before = head;
for (unsigned long j = 0; j < index - 1 && j < why2_list_get_size(list); j++) node_before = node_before -> next; //SCROLL TO THE POSITION
new_node -> next = node_before -> next; //SEW THE LIST BACK
node_before -> next = new_node;
} else //ADD BEFORE THE WHOLE LIST
{
new_node -> next = head;
list -> head = new_node;
}
}
void why2_list_remove(why2_list_t *list, why2_node_t *node) void why2_list_remove(why2_list_t *list, why2_node_t *node)
{ {
if (node == NULL) return; //NULL NODE if (node == NULL) return; //NULL NODE
@ -113,31 +86,8 @@ void why2_list_remove(why2_list_t *list, why2_node_t *node)
list -> head = head; list -> head = head;
//DEALLOCATION //DEALLOCATION
why2_deallocate(node -> value); free(node -> value);
why2_deallocate(node); free(node);
}
void why2_list_remove_at(why2_list_t *list, unsigned long index)
{
if (list -> head == NULL) return; //EMPTY LIST
why2_node_t *node_to_remove;
if (index != 0) //SHOULDN'T BE FIRST
{
why2_node_t *node_before = list -> head;
for (unsigned long j = 0; j < index - 1; j++) node_before = node_before -> next; //SCROLL TO THE POSITION
node_to_remove = node_before -> next;
node_before -> next = node_to_remove -> next;
} else //ADD BEFORE THE WHOLE LIST
{
node_to_remove = list -> head;
list -> head = node_to_remove -> next;
}
why2_deallocate(node_to_remove -> value);
why2_deallocate(node_to_remove);
} }
void why2_list_remove_back(why2_list_t *list) void why2_list_remove_back(why2_list_t *list)
@ -162,8 +112,8 @@ void why2_list_remove_back(why2_list_t *list)
buffer -> next = NULL; //UNLINK buffer -> next = NULL; //UNLINK
} }
why2_deallocate(deallocating_node -> value); free(deallocating_node -> value);
why2_deallocate(deallocating_node); free(deallocating_node);
} }
why2_node_t *why2_list_find(why2_list_t *list, void *value) why2_node_t *why2_list_find(why2_list_t *list, void *value)
@ -202,35 +152,3 @@ unsigned long why2_list_get_size(why2_list_t *list)
return n; return n;
} }
void why2_list_reverse(why2_list_t *list, unsigned long size)
{
if (list -> head == NULL) return; //LIST IS EMPTY
why2_list_t reversed_list = WHY2_LIST_EMPTY;
why2_node_t *buffer = list -> head;
why2_node_t *buffer2;
//REVERSE INTO reversed_list AND DEALLOCATE list
do
{
//COPY
why2_node_t *current_node = why2_malloc(sizeof(why2_node_t));
current_node -> value = why2_malloc(size);
memcpy(current_node -> value, buffer -> value, size);
//INSERT INTO reversed_list
current_node -> next = reversed_list.head; //CHANGE NEXT POINTER
reversed_list.head = current_node; //INSERT
buffer2 = buffer;
buffer = buffer -> next; //ITER
//DEALLOCATE
why2_deallocate(buffer2 -> value);
why2_deallocate(buffer2);
} while (buffer != NULL);
//SET list TO reversed_list
list -> head = reversed_list.head;
}

View File

@ -153,21 +153,8 @@ void *why2_realloc(void *pointer, unsigned long size)
return allocated; return allocated;
} }
void *why2_recalloc(void *pointer, unsigned long size, unsigned long block_size)
{
if (pointer != NULL) why2_deallocate(pointer);
void *allocated = calloc(size, block_size);
push_to_list(allocated, ALLOCATION);
return allocated;
}
char *why2_strdup(char *string) char *why2_strdup(char *string)
{ {
if (string == NULL) return NULL;
char *allocated = strdup(string); char *allocated = strdup(string);
push_to_list(allocated, ALLOCATION); push_to_list(allocated, ALLOCATION);

View File

@ -24,17 +24,16 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <unistd.h> #include <unistd.h>
#include <sys/random.h>
#include <ftw.h> #include <ftw.h>
#include <curl/curl.h> #include <curl/curl.h>
#include <json-c/json.h> #include <json-c/json.h>
#include <git2.h> #include <git2.h>
#include <why2/crypto.h>
#include <why2/flags.h> #include <why2/flags.h>
#include <why2/memory.h> #include <why2/memory.h>
int mod_cb(int a, int b) { return a % (b == 0 ? 1 : b); }
int multiply_cb(int a, int b) { return a * b; } int multiply_cb(int a, int b) { return a * b; }
int subtract_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 sum_cb(int a, int b) { return a + b; }
@ -56,23 +55,15 @@ int removeDirectory(char *path)
void why2_directory(void) void why2_directory(void)
{ {
struct stat st; struct stat st;
char *buffer_2 = why2_replace(WHY2_USER_CONFIG_DIR, "{HOME}", getenv("HOME")); char *buffer = why2_replace(WHY2_CONFIG_DIR, "{USER}", getenv("USER"));
char *buffer = why2_replace(WHY2_CONFIG_DIR, "{HOME}", getenv("HOME"));
//CREATE USER CONFIG FOLDER //CREATE USER CONFIG FOLDER
if (stat(buffer_2, &st) == -1)
{
mkdir(buffer_2, 0700);
}
//CREATE WHY2 CONFIG FOLDER
if (stat(buffer, &st) == -1) if (stat(buffer, &st) == -1)
{ {
mkdir(buffer, 0700); mkdir(buffer, 0700);
} }
//DEALLOCATION //DEALLOCATION
why2_deallocate(buffer_2);
why2_deallocate(buffer); why2_deallocate(buffer);
} }
@ -87,7 +78,7 @@ enum WHY2_EXIT_CODES why2_check_version(void)
int not_found_buffer = 0; int not_found_buffer = 0;
//GET VERSION FILE //GET VERSION FILE
char *version_file = why2_replace(WHY2_VERSIONS_NAME, "{HOME}", getenv("HOME")); char *version_file = why2_replace(WHY2_VERSIONS_NAME, "{USER}", getenv("USER"));
//CURL VARIABLES //CURL VARIABLES
CURL *curl = curl_easy_init(); CURL *curl = curl_easy_init();
@ -99,14 +90,7 @@ enum WHY2_EXIT_CODES why2_check_version(void)
curl_easy_setopt(curl, CURLOPT_TIMEOUT, WHY2_CURL_TIMEOUT); curl_easy_setopt(curl, CURLOPT_TIMEOUT, WHY2_CURL_TIMEOUT);
//DOWNLOAD versions.json //DOWNLOAD versions.json
CURLcode curl_res = curl_easy_perform(curl); curl_easy_perform(curl);
if (curl_res != CURLE_OK && !why2_get_flags().no_output) //ERR
{
fprintf(stderr, "%sDownloading version failed!\n(%s)\n\nExiting...\n", WHY2_CLEAR_SCREEN, curl_easy_strerror(curl_res));
why2_clean_memory("core_version_check");
return WHY2_DOWNLOAD_FAILED;
}
//CLEANUP //CLEANUP
curl_easy_cleanup(curl); curl_easy_cleanup(curl);
@ -289,13 +273,17 @@ void why2_generate_text_key_chain(char *key, int *text_key_chain, int text_key_c
int number_buffer; int number_buffer;
int number_buffer_2 = 0; int number_buffer_2 = 0;
int number_buffer_3 = 0; int number_buffer_3 = 0;
const unsigned long key_length = why2_get_key_length();
int (*cb)(int, int); int (*cb)(int, int);
for (int i = 0; i < text_key_chain_size; i++) 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 //CHECK, IF number_buffer ISN'T GREATER THAN keyLength AND CUT WHY2_UNUSED LENGTH
number_buffer = i % why2_get_key_length(); while (number_buffer >= (int) why2_get_key_length())
{
number_buffer -= why2_get_key_length();
}
//SET tkch VERSION //SET tkch VERSION
switch (why2_get_flags().version) switch (why2_get_flags().version)
@ -307,31 +295,25 @@ void why2_generate_text_key_chain(char *key, int *text_key_chain, int text_key_c
case WHY2_v2: case WHY2_v2:
number_buffer_2 = i; number_buffer_2 = i;
number_buffer_3 = key_length - (number_buffer + (i < text_key_chain_size)); number_buffer_3 = why2_get_key_length() - (number_buffer + (i < text_key_chain_size));
break; break;
case WHY2_v3: case WHY2_v3:
number_buffer_2 = text_key_chain_size - (i + 1); number_buffer_2 = text_key_chain_size - (i + 1);
number_buffer_3 = key_length - (number_buffer + (i < text_key_chain_size)); number_buffer_3 = why2_get_key_length() - (number_buffer + (i < text_key_chain_size));
break;
case WHY2_v4:
number_buffer_2 = text_key_chain_size - (i + 1);
number_buffer_3 = ((((((i ^ number_buffer_2) + ((number_buffer << 3) ^ (number_buffer_2 & 0xF))) * (text_key_chain_size ^ (key_length >> 2))) ^ ((~(number_buffer + text_key_chain_size)) & 0xA7)) + (i % 7)) * (((number_buffer_2 | (i & 0xF)) + (key_length >> 3)) ^ (text_key_chain_size * (number_buffer & 0x3F))) + (((i << 4) ^ (text_key_chain_size >> 1)) & 0x1234) - ((i * number_buffer_2) % (key_length | text_key_chain_size))) % key_length; //gl fucker
break; break;
} }
//FILL textKeyChain //FILL textKeyChain
if (why2_get_flags().version == WHY2_v4 && (number_buffer + 1) % 4 == 0) if ((number_buffer + 1) % 3 == 0)
{
cb = mod_cb;
} else if ((number_buffer + 1) % 3 == 0)
{ {
cb = multiply_cb; cb = multiply_cb;
} else if ((number_buffer + 1) % 2 == 0) }
else if ((number_buffer + 1) % 2 == 0)
{ {
cb = subtract_cb; cb = subtract_cb;
} else }
else
{ {
cb = sum_cb; cb = sum_cb;
} }
@ -438,7 +420,7 @@ char *why2_generate_key(int key_length)
for (int i = 0; i < key_length; i++) for (int i = 0; i < key_length; i++)
{ {
//GET RANDOM NUMBER //GET RANDOM NUMBER
if (!why2_random(&random_buffer, sizeof(unsigned int))) why2_die("getrandom fn failed!"); if (getrandom(&random_buffer, sizeof(unsigned int), GRND_NONBLOCK) == -1) why2_die("getrandom fn failed!");
//SET numberBuffer TO RANDOM NUMBER BETWEEN 0 AND 52 //SET numberBuffer TO RANDOM NUMBER BETWEEN 0 AND 52
number_buffer = (random_buffer % 52) + 1; number_buffer = (random_buffer % 52) + 1;

View File

@ -16,9 +16,8 @@ int main(void)
1, 1,
1, 1,
0, 0,
WHY2_v4, WHY2_v3,
WHY2_OUTPUT_TEXT, WHY2_OUTPUT_TEXT
WHY2_RECOMMENDED_PADDING_RATE(strlen(WHY2_LOGGER_TEST_TEXT))
} }
); );

View File

@ -29,9 +29,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <why2/logger/flags.h> #include <why2/logger/flags.h>
#include <why2/logger/utils.h> #include <why2/logger/utils.h>
#include <why2/crypto.h>
#include <why2/encrypter.h> #include <why2/encrypter.h>
#include <why2/flags.h>
#include <why2/memory.h> #include <why2/memory.h>
#include <why2/misc.h> #include <why2/misc.h>
@ -96,9 +94,6 @@ why2_log_file why2_init_logger(char *directoryPath)
} }
} }
//SET ENCRYPTER FLAGS
if (!why2_get_flags_changed()) __why2_set_flags_anon((why2_input_flags) { 0, 1, 0, WHY2_v4, WHY2_OUTPUT_TEXT, 64 });
//DEALLOCATION //DEALLOCATION
why2_deallocate(dateBuffer); why2_deallocate(dateBuffer);
why2_deallocate(latestBuffer); why2_deallocate(latestBuffer);
@ -126,7 +121,7 @@ void why2_write_log(int loggerFile, char *logMessage)
char *logMessageUsed = why2_strdup(logMessage); char *logMessageUsed = why2_strdup(logMessage);
for (int i = 0; i < (int) strlen(logMessageUsed); i++) for (int i = 0; i < (int) strlen(logMessageUsed); i++)
{ {
if (logMessageUsed[i] == '\n') logMessageUsed[i] = ' '; if (logMessageUsed[i] == '\n') logMessageUsed[i] = '\0';
} }
//VARIABLES //VARIABLES
@ -136,7 +131,8 @@ void why2_write_log(int loggerFile, char *logMessage)
struct tm tm = *localtime(&timeL); struct tm tm = *localtime(&timeL);
why2_log_flags flags = why2_get_log_flags(); why2_log_flags flags = why2_get_log_flags();
if (!why2_get_padding_changed()) __why2_set_padding_anon(WHY2_RECOMMENDED_PADDING_RATE(strlen(logMessageUsed))); //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 if (flags.key != NULL) //ENCRYPT TEXT IF KEY WAS CHANGED
{ {

View File

@ -107,17 +107,6 @@ why2_decrypted_output why2_decrypt_logger(why2_log_file logger)
for (int i = 0; i < lines; i++) //DECRYPT content for (int i = 0; i < lines; i++) //DECRYPT content
{ {
if (!why2_get_padding_changed())
{
printf("A\n");
unsigned long length_buffer = 1;
for (unsigned long j = 0; j < strlen(content[i]); j++)
{
if (content[i][j] == why2_get_encryption_separator()) length_buffer++;
}
__why2_set_padding_anon(length_buffer / 4);
}
outputBuffer = why2_decrypt_text(content[i], why2_get_log_flags().key); //DECRYPT outputBuffer = why2_decrypt_text(content[i], why2_get_log_flags().key); //DECRYPT
contentDecrypted[i] = why2_strdup(outputBuffer.output_text); //COPY contentDecrypted[i] = why2_strdup(outputBuffer.output_text); //COPY