diff --git a/bb64.cpp b/bb64.cpp index 26af5d4..0fed2b6 100644 --- a/bb64.cpp +++ b/bb64.cpp @@ -36,6 +36,41 @@ constexpr unsigned int hash(const char *s, int off = 0) return !s[off] ? 5381 : (hash(s, off + 1) * 33) ^ s[off]; } +std::string tidy(const std::string &str) +{ + std::string result; + bool in_whitespace = false; + for (char c : str) + { + // Remove non-printable characters except for whitespace (space, tab, newline, carriage return) + if ((static_cast(c) < 32 && c != ' ' && c != '\t' && c != '\n' && c != '\r') || static_cast(c) == 127) + { + continue; + } + if (c == ' ' || c == '\t' || c == '\n' || c == '\r') + { + if (!in_whitespace) + { + result += ' '; + in_whitespace = true; + } + } + else + { + result += c; + in_whitespace = false; + } + } + // Remove leading whitespace + size_t start = result.find_first_not_of(' '); + if (start == std::string::npos) + return ""; + // Remove trailing whitespace + size_t end = result.find_last_not_of(' '); + return result.substr(start, end - start + 1); +} + + std::string get_arch() { // determine the architecture of the system @@ -108,7 +143,10 @@ int main(int argc, char *argv[]) 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 + + bb64 -e COMMAND Encodes the command and prints the base64 encoded result + bb64 -e Encodes the command provided on stdin and prints the result + bb64 -u Updates bb64 to the latest version (uses docker) )" << std::endl; @@ -121,11 +159,25 @@ Usage: { if (mode == "-u") return update_bb64(); + else if (mode == "-e") + { + std::ostringstream oss; + while (std::cin) + { + std::string line; + std::getline(std::cin, line); + oss << line << std::endl; + } + std::string tidier = tidy(oss.str()); + std::cout << base64_encode(tidier) << std::endl; + return 0; + } else return decode_and_run(mode); } std::ostringstream oss; + std::string tidier; switch (hash(mode.c_str())) { @@ -138,7 +190,8 @@ Usage: case hash("-e"): for (int i = 2; i < argc; ++i) oss << (i > 2 ? " " : "") << argv[i]; - std::cout << base64_encode(oss.str()) << std::endl; + tidier = tidy(oss.str()); + std::cout << base64_encode(tidier) << std::endl; break; default: std::cerr << "Invalid mode: " << mode << std::endl; diff --git a/version.h b/version.h index 815cfe9..e72b3ca 100644 --- a/version.h +++ b/version.h @@ -1 +1 @@ -static const char *VERSION = "33"; +static const char *VERSION = "34";