#include "../common/color.h" #include "crypt.h" #include #include #include #include #include #include #include #include namespace pupes_message_client_lib { void error(std::string msg) { std::cerr << msg << ": " << strerror(errno) << std::endl; exit(EXIT_FAILURE); } // TODO: CHANGE THIS TO OS KEYRING EVP_PKEY *SaveOrGetKeypair(EVP_PKEY *keypair = nullptr) { std::string home = std::getenv("HOME"); if (home.empty()) { error("HOME environment variable not set.\n"); } std::string savedir_path = home; savedir_path.append("/.local/share/pupes-message"); if (!std::filesystem::exists(savedir_path)) { if (!std::filesystem::create_directories(savedir_path)) { error("Failed to create directory: " + savedir_path + "\n"); } } std::string private_key_file_path = savedir_path + "/private_key.pem"; if (keypair != nullptr) { FILE *private_key_file = fopen(private_key_file_path.c_str(), "wb"); if (private_key_file == nullptr) { error("Failed to open private key file for writing.\n"); } PEM_write_PrivateKey(private_key_file, keypair, nullptr, nullptr, 0, nullptr, nullptr); fclose(private_key_file); return nullptr; } else { FILE *private_key_file = fopen(private_key_file_path.c_str(), "rb"); if (private_key_file == nullptr) { if (errno == ENOENT) { std::clog << BLUE "[LOG]" RESET " Private key file not found. Generating a new keypair.\n"; return generate_keypair(); } error("Failed to open private key file for reading.\n"); } keypair = PEM_read_PrivateKey(private_key_file, nullptr, nullptr, nullptr); if (keypair == nullptr) { fclose(private_key_file); error("Failed to read private key from file.\n"); } fclose(private_key_file); return keypair; } } } // namespace pupes_message_client_lib