bb64/bb64.cpp
Your Name bb355cf4ac Tidy
2025-05-12 19:48:56 +12:00

88 lines
2.3 KiB
C++

#include <iostream>
#include <string>
#include <vector>
#include <unistd.h>
#include <cstring>
#include <sstream>
#include "version.h"
#include "b64ed.hpp"
// Recursively decode and print if nested bb64 command is found
void recursive_print(const std::string &decoded)
{
std::cout << decoded << std::endl;
size_t pos = decoded.find("bb64 ");
if (pos != std::string::npos)
{
std::istringstream iss(decoded.substr(pos));
std::string cmd, arg;
iss >> cmd >> arg;
if (cmd == "bb64" && !arg.empty())
{
std::string nested = base64_decode(arg);
std::cout << " ";
std::cout << "nested: " << nested << std::endl;
recursive_print(nested);
}
}
}
constexpr unsigned int hash(const char *s, int off = 0)
{
return !s[off] ? 5381 : (hash(s, off + 1) * 33) ^ s[off];
}
int main(int argc, char *argv[])
{
if (argc < 2)
{
std::cerr << "bb64 version " << VERSION << ", by J842." << std::endl;
// heredoc for instructions
std::cerr << R"(
Usage:
bb64 BASE64COMMAND Decodes and runs the command
bb64 -[i|d] BASE64COMMAND Displays the decoded command
bb64 -e COMMAND Encodes the command and prints the result
)" << std::endl;
return -1;
}
if (argc == 2)
{
// Default: decode and run
std::string decoded = base64_decode(argv[1]);
if (decoded.empty())
{
std::cerr << "Failed to decode base64 command." << std::endl;
return -1;
}
// Replace current process with bash -c "decoded"
execlp("bash", "bash", "-c", decoded.c_str(), (char *)nullptr);
// If execlp returns, there was an error
std::cerr << "Failed to execute command." << std::endl;
return -1;
}
std::string mode = argv[1];
std::ostringstream oss;
switch (hash(mode.c_str()))
{
case hash("-i"):
case hash("-d"):
recursive_print(base64_decode(argv[2]));
break;
case hash("-e"):
for (int i = 2; i < argc; ++i)
oss << (i > 2 ? " " : "") << argv[i];
std::cout << base64_encode(oss.str()) << std::endl;
break;
default:
std::cerr << "Invalid mode: " << mode << std::endl;
return -1;
};
}