440 lines
14 KiB
C++
440 lines
14 KiB
C++
#include "TerminalConsole.h"
|
|
|
|
#include <gtest/gtest.h>
|
|
|
|
#include <cerrno>
|
|
#include <cstdlib>
|
|
#include <optional>
|
|
#include <stdexcept>
|
|
#include <string>
|
|
#include <string_view>
|
|
#include <thread>
|
|
|
|
#ifndef _WIN32
|
|
#include <csignal>
|
|
#include <fcntl.h>
|
|
#include <poll.h>
|
|
#include <sys/ioctl.h>
|
|
#include <sys/wait.h>
|
|
#include <termios.h>
|
|
#include <unistd.h>
|
|
|
|
namespace
|
|
{
|
|
using Bilicraft::TerminalConsole;
|
|
|
|
void Put(int fd, std::string_view text)
|
|
{
|
|
while (!text.empty())
|
|
{
|
|
const auto count = write(fd, text.data(), text.size());
|
|
if (count < 0 && errno == EINTR) continue;
|
|
if (count <= 0) throw std::runtime_error("test write failed");
|
|
text.remove_prefix(static_cast<std::size_t>(count));
|
|
}
|
|
}
|
|
|
|
std::string Drain(int fd)
|
|
{
|
|
std::string result;
|
|
char bytes[2048];
|
|
for (;;)
|
|
{
|
|
const auto count = read(fd, bytes, sizeof(bytes));
|
|
if (count > 0) result.append(bytes, static_cast<std::size_t>(count));
|
|
else if (count < 0 && errno == EINTR) continue;
|
|
else break;
|
|
}
|
|
return result;
|
|
}
|
|
|
|
class Pipe
|
|
{
|
|
public:
|
|
Pipe()
|
|
{
|
|
if (pipe(fds) != 0) throw std::runtime_error("pipe failed");
|
|
if (fcntl(fds[0], F_SETFL, O_NONBLOCK) < 0) throw std::runtime_error("fcntl failed");
|
|
}
|
|
~Pipe() { if (fds[0] >= 0) close(fds[0]); if (fds[1] >= 0) close(fds[1]); }
|
|
void CloseWriter() { close(fds[1]); fds[1] = -1; }
|
|
int fds[2]{-1, -1};
|
|
};
|
|
|
|
class Pty : public ::testing::Test
|
|
{
|
|
protected:
|
|
void SetUp() override
|
|
{
|
|
if (const char *value = std::getenv("TERM")) oldTerm = value;
|
|
ASSERT_EQ(setenv("TERM", "xterm-256color", 1), 0);
|
|
master = posix_openpt(O_RDWR | O_NOCTTY | O_NONBLOCK);
|
|
if (master < 0) GTEST_SKIP() << "No POSIX PTY available";
|
|
ASSERT_EQ(grantpt(master), 0);
|
|
ASSERT_EQ(unlockpt(master), 0);
|
|
const char *name = ptsname(master);
|
|
ASSERT_NE(name, nullptr);
|
|
slave = open(name, O_RDWR | O_NOCTTY);
|
|
ASSERT_GE(slave, 0);
|
|
Size(24, 80);
|
|
ASSERT_EQ(tcgetattr(slave, &original), 0);
|
|
}
|
|
void TearDown() override
|
|
{
|
|
if (slave >= 0) { tcsetattr(slave, TCSANOW, &original); close(slave); }
|
|
if (master >= 0) close(master);
|
|
if (oldTerm) setenv("TERM", oldTerm->c_str(), 1);
|
|
else unsetenv("TERM");
|
|
}
|
|
void Size(unsigned short rows, unsigned short columns)
|
|
{
|
|
winsize size{};
|
|
size.ws_row = rows;
|
|
size.ws_col = columns;
|
|
ASSERT_EQ(ioctl(slave, TIOCSWINSZ, &size), 0);
|
|
}
|
|
void Input(std::string_view text)
|
|
{
|
|
Put(master, text);
|
|
pollfd item{slave, POLLIN, 0};
|
|
ASSERT_GT(poll(&item, 1, 1000), 0);
|
|
}
|
|
int Available()
|
|
{
|
|
int count = -1;
|
|
EXPECT_EQ(ioctl(slave, FIONREAD, &count), 0);
|
|
return count;
|
|
}
|
|
void ExpectRestored()
|
|
{
|
|
termios current{};
|
|
ASSERT_EQ(tcgetattr(slave, ¤t), 0);
|
|
EXPECT_EQ(current.c_iflag, original.c_iflag);
|
|
EXPECT_EQ(current.c_oflag, original.c_oflag);
|
|
EXPECT_EQ(current.c_cflag, original.c_cflag);
|
|
EXPECT_EQ(current.c_lflag, original.c_lflag);
|
|
EXPECT_EQ(cfgetispeed(¤t), cfgetispeed(&original));
|
|
EXPECT_EQ(cfgetospeed(¤t), cfgetospeed(&original));
|
|
for (std::size_t i = 0; i < NCCS; ++i) EXPECT_EQ(current.c_cc[i], original.c_cc[i]);
|
|
}
|
|
int master = -1, slave = -1;
|
|
termios original{};
|
|
std::optional<std::string> oldTerm;
|
|
};
|
|
|
|
TEST_F(Pty, PlainBeforeStartThenRawAndFullRestoration)
|
|
{
|
|
{
|
|
TerminalConsole console(slave, slave, slave);
|
|
console.Out() << "login\n";
|
|
EXPECT_EQ(Drain(master).find('\033'), std::string::npos);
|
|
console.Start();
|
|
ASSERT_TRUE(console.IsSplit());
|
|
termios raw{};
|
|
ASSERT_EQ(tcgetattr(slave, &raw), 0);
|
|
EXPECT_EQ(raw.c_lflag & (ICANON | ECHO | IEXTEN), 0U);
|
|
EXPECT_NE(raw.c_lflag & ISIG, 0U);
|
|
EXPECT_EQ(raw.c_iflag & IXON, 0U);
|
|
EXPECT_EQ(raw.c_cc[VMIN], 0);
|
|
EXPECT_EQ(raw.c_cc[VTIME], 0);
|
|
#ifdef VQUIT
|
|
EXPECT_EQ(raw.c_cc[VQUIT], _POSIX_VDISABLE);
|
|
#endif
|
|
#ifdef VSUSP
|
|
EXPECT_EQ(raw.c_cc[VSUSP], _POSIX_VDISABLE);
|
|
#endif
|
|
const auto screen = Drain(master);
|
|
EXPECT_NE(screen.find("\033[1;22r"), std::string::npos);
|
|
EXPECT_NE(screen.find("\033[23;1H"), std::string::npos);
|
|
EXPECT_NE(screen.find("\033[24;1H"), std::string::npos);
|
|
EXPECT_EQ(screen.find("?1049"), std::string::npos);
|
|
console.Start(); // no second mode switch or duplicated prompt
|
|
EXPECT_TRUE(Drain(master).empty());
|
|
}
|
|
ExpectRestored();
|
|
const auto cleanup = Drain(master);
|
|
EXPECT_NE(cleanup.find("\033[r"), std::string::npos);
|
|
EXPECT_NE(cleanup.find("\033[?25h"), std::string::npos);
|
|
EXPECT_NE(fcntl(slave, F_GETFD), -1); // borrowed descriptor is still open
|
|
}
|
|
|
|
TEST_F(Pty, ExceptionUnwindingRestoresTerminal)
|
|
{
|
|
try
|
|
{
|
|
TerminalConsole console(slave, slave, slave);
|
|
console.Start();
|
|
ASSERT_TRUE(console.IsSplit());
|
|
throw std::runtime_error("application failure");
|
|
}
|
|
catch (const std::runtime_error &) {}
|
|
ExpectRestored();
|
|
}
|
|
|
|
TEST_F(Pty, BusyConsumesNothingAndSubmissionDoesNotReadAhead)
|
|
{
|
|
TerminalConsole console(slave, slave, slave);
|
|
console.Start();
|
|
Drain(master);
|
|
console.SetInputEnabled(false);
|
|
Input("first\nsecond\n");
|
|
const int before = Available();
|
|
EXPECT_FALSE(console.PollLine());
|
|
console.Tick();
|
|
EXPECT_EQ(Available(), before);
|
|
EXPECT_NE(Drain(master).find("busy / pending"), std::string::npos);
|
|
console.SetInputEnabled(true);
|
|
EXPECT_EQ(console.PollLine(), std::optional<std::string>("first"));
|
|
EXPECT_EQ(Available(), 7);
|
|
EXPECT_EQ(console.PollLine(), std::optional<std::string>("second"));
|
|
}
|
|
|
|
TEST_F(Pty, ArrowHistoryDraftAndUnicodeRemainEditableAcrossThreadedLogs)
|
|
{
|
|
TerminalConsole console(slave, slave, slave);
|
|
console.Start();
|
|
Input("old\n");
|
|
ASSERT_EQ(console.PollLine(), std::optional<std::string>("old"));
|
|
Input("draft\033[A");
|
|
EXPECT_FALSE(console.PollLine());
|
|
Drain(master);
|
|
std::thread logger([&console] { console.WriteLog("network log\n"); });
|
|
logger.join();
|
|
const auto logged = Drain(master);
|
|
EXPECT_NE(logged.find("network log"), std::string::npos);
|
|
EXPECT_NE(logged.find(">>> old"), std::string::npos);
|
|
Input("\033[B\n");
|
|
EXPECT_EQ(console.PollLine(), std::optional<std::string>("draft"));
|
|
Input("中文\033[D\177\n");
|
|
EXPECT_EQ(console.PollLine(), std::optional<std::string>("文"));
|
|
}
|
|
|
|
TEST_F(Pty, StripsFragmentedAnsiOscAndControlCharactersFromLogs)
|
|
{
|
|
TerminalConsole console(slave, slave, slave);
|
|
console.Start();
|
|
Drain(master);
|
|
console.WriteLog("before\033[");
|
|
console.WriteLog("999;999Hafter\033]52;c;BAD");
|
|
console.WriteLog("\aend\033Psecret\033\\\x01\n");
|
|
const auto screen = Drain(master);
|
|
EXPECT_NE(screen.find("before"), std::string::npos);
|
|
EXPECT_NE(screen.find("after"), std::string::npos);
|
|
EXPECT_NE(screen.find("end"), std::string::npos);
|
|
EXPECT_EQ(screen.find("999;999H"), std::string::npos);
|
|
EXPECT_EQ(screen.find("52;c;BAD"), std::string::npos);
|
|
EXPECT_EQ(screen.find("secret"), std::string::npos);
|
|
EXPECT_EQ(screen.find('\x01'), std::string::npos);
|
|
EXPECT_NE(screen.find("\0338"), std::string::npos);
|
|
EXPECT_NE(screen.find("\0337"), std::string::npos);
|
|
}
|
|
|
|
TEST_F(Pty, MalformedLogEscapesRecoverAtNewlineAndPreserveUtf8Fragments)
|
|
{
|
|
TerminalConsole console(slave, slave, slave);
|
|
console.Start();
|
|
Drain(master);
|
|
console.WriteLog("\033]unterminated\nvisible-one\n");
|
|
console.WriteLog("\033[12;\nvisible-two\n");
|
|
console.WriteLog("\xe4\xb8");
|
|
console.WriteLog("\xad\xe6\x96\x87\n");
|
|
const auto screen = Drain(master);
|
|
EXPECT_EQ(screen.find("unterminated"), std::string::npos);
|
|
EXPECT_NE(screen.find("visible-one"), std::string::npos);
|
|
EXPECT_NE(screen.find("visible-two"), std::string::npos);
|
|
EXPECT_NE(screen.find("中文"), std::string::npos);
|
|
}
|
|
|
|
TEST_F(Pty, RedirectedStderrContainsOnlyOriginalLogBytes)
|
|
{
|
|
Pipe errors;
|
|
TerminalConsole console(slave, slave, errors.fds[1]);
|
|
console.Start();
|
|
Drain(master);
|
|
console.Err() << "error " << 42 << '\n';
|
|
EXPECT_EQ(Drain(errors.fds[0]), "error 42\n");
|
|
EXPECT_TRUE(Drain(master).empty());
|
|
}
|
|
|
|
TEST_F(Pty, BrokenRedirectedPipeDoesNotRaiseSigpipeOrPreventCleanup)
|
|
{
|
|
Pipe errors;
|
|
close(errors.fds[0]);
|
|
errors.fds[0] = -1;
|
|
const pid_t child = fork();
|
|
ASSERT_GE(child, 0);
|
|
if (child == 0)
|
|
{
|
|
struct sigaction action{};
|
|
action.sa_handler = SIG_DFL;
|
|
sigemptyset(&action.sa_mask);
|
|
sigaction(SIGPIPE, &action, nullptr);
|
|
sigset_t mask;
|
|
sigemptyset(&mask);
|
|
sigaddset(&mask, SIGPIPE);
|
|
sigprocmask(SIG_UNBLOCK, &mask, nullptr);
|
|
{
|
|
TerminalConsole console(slave, slave, errors.fds[1]);
|
|
console.Start();
|
|
console.WriteLog("closed destination\n", true);
|
|
}
|
|
_exit(0);
|
|
}
|
|
int status = 0;
|
|
ASSERT_EQ(waitpid(child, &status, 0), child);
|
|
ASSERT_TRUE(WIFEXITED(status));
|
|
EXPECT_EQ(WEXITSTATUS(status), 0);
|
|
ExpectRestored();
|
|
}
|
|
|
|
TEST_F(Pty, ResizesMarginsAndClipsChineseLineWithoutWrapping)
|
|
{
|
|
TerminalConsole console(slave, slave, slave);
|
|
console.Start();
|
|
Drain(master);
|
|
Size(8, 20);
|
|
console.Tick();
|
|
EXPECT_NE(Drain(master).find("\033[1;6r"), std::string::npos);
|
|
Input("中文中文中文中文中文中文中文");
|
|
EXPECT_FALSE(console.PollLine());
|
|
const auto narrow = Drain(master);
|
|
// 19 usable columns - 4 prompt columns = 15; seven CJK glyphs fit.
|
|
EXPECT_EQ(narrow.find("中文中文中文中文"), std::string::npos);
|
|
EXPECT_NE(narrow.find("\033[8;"), std::string::npos);
|
|
Size(2, 5);
|
|
console.Tick();
|
|
Drain(master);
|
|
console.WriteLog("must not overwrite editor\n");
|
|
EXPECT_EQ(Drain(master).find("must not overwrite editor"), std::string::npos);
|
|
Size(30, 100);
|
|
console.Tick();
|
|
EXPECT_NE(Drain(master).find("\033[1;28r"), std::string::npos);
|
|
Input("\n");
|
|
EXPECT_EQ(console.PollLine(), std::optional<std::string>("中文中文中文中文中文中文中文"));
|
|
}
|
|
|
|
TEST_F(Pty, CtrlDAndHangupLatchEof)
|
|
{
|
|
{
|
|
TerminalConsole console(slave, slave, slave);
|
|
console.Start();
|
|
Input("\004");
|
|
EXPECT_FALSE(console.PollLine());
|
|
EXPECT_TRUE(console.IsEof());
|
|
EXPECT_FALSE(console.PollLine());
|
|
}
|
|
ExpectRestored();
|
|
TerminalConsole console(slave, slave, slave);
|
|
console.Start();
|
|
close(master);
|
|
master = -1;
|
|
EXPECT_NO_THROW(console.PollLine());
|
|
EXPECT_TRUE(console.IsEof());
|
|
EXPECT_FALSE(console.PollLine());
|
|
}
|
|
|
|
TEST_F(Pty, DumbSmallOrDifferentOutputFallsBackWithoutAnsi)
|
|
{
|
|
setenv("TERM", "dumb", 1);
|
|
{
|
|
TerminalConsole console(slave, slave, slave);
|
|
console.Start();
|
|
EXPECT_FALSE(console.IsSplit());
|
|
EXPECT_EQ(Drain(master), ">>> ");
|
|
ExpectRestored();
|
|
}
|
|
setenv("TERM", "xterm", 1);
|
|
Size(3, 19);
|
|
{
|
|
TerminalConsole console(slave, slave, slave);
|
|
console.Start();
|
|
EXPECT_FALSE(console.IsSplit());
|
|
EXPECT_EQ(Drain(master), ">>> ");
|
|
ExpectRestored();
|
|
}
|
|
Size(24, 80);
|
|
Pipe output;
|
|
TerminalConsole console(slave, output.fds[1], output.fds[1]);
|
|
console.Start();
|
|
EXPECT_FALSE(console.IsSplit());
|
|
EXPECT_EQ(Drain(output.fds[0]), ">>> ");
|
|
ExpectRestored();
|
|
}
|
|
|
|
volatile std::sig_atomic_t interrupted = 0;
|
|
void NotifyInterrupt(int) { interrupted = 1; }
|
|
|
|
TEST_F(Pty, SigintNotificationThenNormalUnwindRestoresTermios)
|
|
{
|
|
int ready[2];
|
|
ASSERT_EQ(pipe(ready), 0);
|
|
const pid_t child = fork();
|
|
ASSERT_GE(child, 0);
|
|
if (child == 0)
|
|
{
|
|
close(ready[0]);
|
|
sigset_t blocked, previous;
|
|
sigemptyset(&blocked);
|
|
sigaddset(&blocked, SIGINT);
|
|
sigprocmask(SIG_BLOCK, &blocked, &previous);
|
|
struct sigaction action{};
|
|
action.sa_handler = NotifyInterrupt;
|
|
sigemptyset(&action.sa_mask);
|
|
sigaction(SIGINT, &action, nullptr);
|
|
{
|
|
TerminalConsole console(slave, slave, slave);
|
|
console.Start();
|
|
const char state = console.IsSplit() ? 'Y' : 'N';
|
|
if (write(ready[1], &state, 1) != 1) _exit(3);
|
|
while (!interrupted) sigsuspend(&previous);
|
|
}
|
|
_exit(0);
|
|
}
|
|
close(ready[1]);
|
|
pollfd item{ready[0], POLLIN, 0};
|
|
const int readyResult = poll(&item, 1, 3000);
|
|
char state = 0;
|
|
const auto count = readyResult > 0 ? read(ready[0], &state, 1) : -1;
|
|
close(ready[0]);
|
|
// Always reap, even if startup fails, so a failed test leaves no child.
|
|
kill(child, count == 1 && state == 'Y' ? SIGINT : SIGKILL);
|
|
int status = 0;
|
|
ASSERT_EQ(waitpid(child, &status, 0), child);
|
|
ASSERT_EQ(count, 1);
|
|
ASSERT_EQ(state, 'Y');
|
|
ASSERT_TRUE(WIFEXITED(status));
|
|
EXPECT_EQ(WEXITSTATUS(status), 0);
|
|
ExpectRestored();
|
|
}
|
|
|
|
TEST(TerminalConsoleTest, PipeFallbackPromptsOnceAndNeverConsumesWhileBusy)
|
|
{
|
|
Pipe input, output;
|
|
TerminalConsole console(input.fds[0], output.fds[1], output.fds[1]);
|
|
console.Out() << "login\n";
|
|
EXPECT_EQ(Drain(output.fds[0]), "login\n");
|
|
console.SetInputEnabled(false);
|
|
console.Start();
|
|
EXPECT_FALSE(console.IsSplit());
|
|
EXPECT_TRUE(Drain(output.fds[0]).empty());
|
|
Put(input.fds[1], "first\nsecond\n");
|
|
EXPECT_FALSE(console.PollLine());
|
|
console.SetInputEnabled(true);
|
|
console.Tick();
|
|
console.Tick();
|
|
EXPECT_EQ(Drain(output.fds[0]), ">>> ");
|
|
EXPECT_EQ(console.PollLine(), std::optional<std::string>("first"));
|
|
int remaining = 0;
|
|
ASSERT_EQ(ioctl(input.fds[0], FIONREAD, &remaining), 0);
|
|
EXPECT_EQ(remaining, 7);
|
|
console.Tick();
|
|
EXPECT_EQ(Drain(output.fds[0]), "\n>>> ");
|
|
EXPECT_EQ(console.PollLine(), std::optional<std::string>("second"));
|
|
input.CloseWriter();
|
|
EXPECT_FALSE(console.PollLine());
|
|
EXPECT_TRUE(console.IsEof());
|
|
EXPECT_EQ(Drain(output.fds[0]).find('\033'), std::string::npos);
|
|
}
|
|
} // namespace
|
|
#endif
|