diff --git a/bin/base64.c b/bin/base64.c index 90a589e..f419056 100644 --- a/bin/base64.c +++ b/bin/base64.c @@ -3,6 +3,11 @@ # define MINGW #endif +// Test for Windows. +#if defined(_WIN32) || defined(_WIN64) +# define WIN +#endif + // Decide if the writev(2) system call needs to be emulated as a series of // write(2) calls. At least MinGW does not support writev(2). #ifdef MINGW @@ -24,6 +29,11 @@ #include #include +// Include the Windows API. +#ifdef WIN +# include +#endif + #include "../include/libbase64.h" // Size of the buffer for the "raw" (not base64-encoded) data in bytes. @@ -303,7 +313,7 @@ write_wrapped (const struct config *config, char *buf, size_t len) } static bool -encode (const struct config *config, struct buffer *buf) +encode_inner (const struct config *config, struct buffer *buf) { size_t nread, nout; struct base64_state state; @@ -346,6 +356,47 @@ encode (const struct config *config, struct buffer *buf) return true; } +static bool +encode (const struct config *config, struct buffer *buf) +{ +#ifdef WIN + DWORD dwMode; + + // Get the standard output handle. + HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); + + // Check for errors. + if (hOut == INVALID_HANDLE_VALUE) { + fprintf(stderr, "GetStdHandle: err#%d\n", GetLastError()); + return false; + } + + // Save the current output mode. + if (!GetConsoleMode(hOut, &dwMode)) { + fprintf(stderr, "GetConsoleMode: err#%d\n", GetLastError()); + return false; + } + + // Disable newline mangling. + if (!SetConsoleMode(hOut, dwMode | DISABLE_NEWLINE_AUTO_RETURN)) { + fprintf(stderr, "SetConsoleMode: err#%d\n", GetLastError()); + return false; + } +#endif + + const bool ret = encode_inner(config, buf); + +#ifdef WIN + + // Restore the original console settings. + if (!SetConsoleMode(hOut, dwMode)) { + fprintf(stderr, "SetConsoleMode: err#%d\n", GetLastError()); + } +#endif + + return ret; +} + static inline size_t find_garbage (const char *p, const size_t avail) {