Files

369 lines
15 KiB
Plaintext

// SPDX-License-Identifier: GPL-3.0-or-later
#include "DriveWireShell.h"
#include "DriveWireTerminal.h"
#include <algorithm>
#include <array>
#include <atomic>
#include <cerrno>
#include <chrono>
#include <csignal>
#include <deque>
#include <fcntl.h>
#include <limits.h>
#include <mutex>
#include <poll.h>
#include <pwd.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#include <termios.h>
#include <thread>
#include <unistd.h>
#include <util.h>
#include <vector>
namespace VCC::Mac {
namespace {
using Transport = Devices::DriveWireTransport;
using State = Transport::State;
using namespace std::chrono_literals;
constexpr std::size_t queueLimit = 65536;
struct Child {
pid_t pid = -1;
int master = -1;
~Child() {
if (master >= 0) ::close(master);
}
};
// Spawn directly into a fresh session. The child gets only its three tty
// descriptors and a small interactive environment. No login helper, command
// string, or user-supplied executable path is involved.
bool spawnShell(Child& child, DriveWireShell::StartupFiles startup) {
passwd record{}, *user = nullptr;
std::array<char, 32768> account{};
if (::getpwuid_r(::getuid(), &record, account.data(), account.size(), &user) || !user) return false;
std::string home = record.pw_dir, shell = record.pw_shell, name = record.pw_name;
if (home.empty() || home.front() != '/' || shell.empty() || shell.front() != '/') return false;
int slave = -1;
winsize size{24, 80, 0, 0};
char tty[PATH_MAX]{};
if (::openpty(&child.master, &slave, tty, nullptr, &size) != 0) return false;
if (::fcntl(child.master, F_SETFD, FD_CLOEXEC) < 0 || ::fcntl(slave, F_SETFD, FD_CLOEXEC) < 0 ||
::fcntl(child.master, F_SETFL, O_NONBLOCK) < 0) {
::close(slave);
return false;
}
termios modes{};
if (::tcgetattr(slave, &modes) == 0) {
modes.c_cc[VERASE] = 8; // CoCo backspace
::tcsetattr(slave, TCSANOW, &modes);
}
std::string term = "TERM=vt100", path = "PATH=/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin";
std::string dir = "HOME=" + home, login = "LOGNAME=" + name, uid = "USER=" + name, sh = "SHELL=" + shell;
std::string locale = "LANG=en_US.UTF-8", prompt = "PS1=$ ", history = "HISTFILE=/dev/null";
// Ordinary sessions use the account's interactive login shell. Only
// the integration tests suppress personal startup scripts and history.
auto base = shell.substr(shell.find_last_of('/') + 1);
bool isolated = startup == DriveWireShell::StartupFiles::isolatedTest;
if (isolated && base != "zsh" && base != "bash") { shell = "/bin/sh"; sh = "SHELL=" + shell; base = "sh"; }
std::vector<std::string> options{isolated ? base : "-" + base};
if (isolated && base == "zsh") options.insert(options.end(), {"-f", "-o", "no_zle"});
if (isolated && base == "bash") options.insert(options.end(), {"--noprofile", "--norc", "--noediting"});
options.emplace_back("-i");
std::vector<char*> args;
for (auto& option : options) args.push_back(option.data());
args.push_back(nullptr);
std::vector<char*> env{dir.data(), login.data(), uid.data(), sh.data(), term.data(), path.data(), locale.data()};
if (isolated) { env.push_back(prompt.data()); env.push_back(history.data()); }
env.push_back(nullptr);
// These pointers and limits are computed before fork. The child of the
// multithreaded Mac app uses only descriptor/signal syscalls and execve.
auto executable = shell.c_str();
auto directory = home.c_str();
auto arguments = args.data();
auto environment = env.data();
const int maxFD = static_cast<int>(::sysconf(_SC_OPEN_MAX));
int handshake[2]{};
if (maxFD < 3 || ::pipe(handshake) < 0) { ::close(slave); return false; }
if (::fcntl(handshake[0], F_SETFD, FD_CLOEXEC) < 0 || ::fcntl(handshake[1], F_SETFD, FD_CLOEXEC) < 0) {
::close(slave); ::close(handshake[0]); ::close(handshake[1]); return false;
}
sigset_t mask;
sigemptyset(&mask);
struct sigaction defaults{};
defaults.sa_handler = SIG_DFL;
sigemptyset(&defaults.sa_mask);
child.pid = ::fork();
if (child.pid == 0) {
::close(handshake[0]);
bool ok = ::setsid() >= 0 && ::ioctl(slave, TIOCSCTTY, 0) == 0;
for (int fd = 0; ok && fd < 3; ++fd)
ok = ::dup2(slave, fd) >= 0 && ::fcntl(fd, F_SETFD, 0) == 0;
for (int fd = 3; fd < maxFD; ++fd) if (fd != handshake[1]) ::close(fd);
for (int signal = 1; signal < NSIG; ++signal) {
if (signal != SIGKILL && signal != SIGSTOP) ::sigaction(signal, &defaults, nullptr);
}
::sigprocmask(SIG_SETMASK, &mask, nullptr);
if (ok && ::chdir(directory) == 0) ::execve(executable, arguments, environment);
const char failed = 1;
(void)::write(handshake[1], &failed, 1);
_exit(127);
}
::close(slave);
::close(handshake[1]);
char failure;
ssize_t result;
do { result = ::read(handshake[0], &failure, 1); } while (result < 0 && errno == EINTR);
::close(handshake[0]);
if (child.pid < 0) return false;
if (result == 0) return true;
while (::waitpid(child.pid, nullptr, 0) < 0 && errno == EINTR) {}
return false;
}
void hangup(Child& child) {
// Closing a controlling tty sends HUP to its foreground group. Also signal
// the shell's own group when a foreground job has taken control. Keep its
// pid unreaped until sending signals is finished to avoid pid reuse.
pid_t foreground = ::tcgetpgrp(child.master);
if (foreground > 0 && foreground != child.pid && ::getsid(foreground) == child.pid) {
::kill(-foreground, SIGHUP);
::kill(-foreground, SIGCONT);
// Explicit revocation must also stop a foreground program that traps
// terminal hangups. Limit the signal to the shell's own session.
if (::getsid(foreground) == child.pid) ::kill(-foreground, SIGKILL);
}
::kill(-child.pid, SIGHUP);
::kill(-child.pid, SIGCONT);
::close(child.master);
child.master = -1;
for (unsigned i = 0; i < 20; ++i) {
int status = 0;
pid_t done = ::waitpid(child.pid, &status, WNOHANG);
if (done == child.pid || (done < 0 && errno == ECHILD)) return;
std::this_thread::sleep_for(10ms);
}
::kill(child.pid, SIGKILL);
while (::waitpid(child.pid, nullptr, 0) < 0 && errno == EINTR) {}
}
// Option (the CoCo Alt key) distinguishes cursor keys from OS-9 editing
// characters. The stock telnet client sends the corresponding high-bit codes.
char cursorDirection(std::uint8_t key) {
switch (key) {
case 0x8c: return 'A'; // up
case 0x8a: return 'B'; // down
case 0x89: return 'C'; // right
case 0x88: return 'D'; // left
default: return 0;
}
}
class Terminal {
public:
std::atomic<State> state{State::connecting};
std::atomic<bool> stopped{false};
std::atomic<bool> launched{false};
const std::chrono::steady_clock::time_point expires = std::chrono::steady_clock::now() + 2min;
bool waiting() const {
return !launched && !stopped && state == State::connecting && std::chrono::steady_clock::now() < expires;
}
State transportState() const {
if (!launched && !waiting()) return State::failed;
return stopped ? State::closed : state.load();
}
void cancel() {
std::lock_guard lock(mutex);
stopped = true;
incoming.clear();
outgoing.clear();
}
std::size_t read(std::uint8_t* bytes, std::size_t count) {
std::lock_guard lock(mutex);
if (stopped) return 0;
count = std::min(count, incoming.size());
std::copy_n(incoming.begin(), count, bytes);
incoming.erase(incoming.begin(), incoming.begin() + count);
return count;
}
bool write(const std::uint8_t* bytes, std::size_t count) {
std::lock_guard lock(mutex);
if (stopped || state != State::connected || count > queueLimit - outgoing.size()) return false;
// The stock OS-9 telnet client sends its abort byte for CoCo Break
// (Mac Escape). Backspace and Tab also double as left/right on the
// wire; keep their normal shell meanings.
const auto arrows = std::count_if(bytes, bytes + count, cursorDirection);
if (count + 2 * arrows > queueLimit - outgoing.size()) return false;
for (std::size_t i = 0; i < count; ++i) {
if (auto direction = cursorDirection(bytes[i])) {
outgoing.push_back(0x1b);
outgoing.push_back(applicationKeys ? 'O' : '[');
outgoing.push_back(direction);
} else {
outgoing.push_back(bytes[i] == 0x05 ? 0x1b : bytes[i]);
}
}
return true;
}
void run(DriveWireShell::StartupFiles startup) {
Child child;
if (stopped || !spawnShell(child, startup)) { state = State::failed; return; }
state = State::connected;
bool reaped = false;
DriveWireTerminal terminal;
std::vector<std::uint8_t> display;
std::size_t displayOffset = 0;
while (!stopped) {
std::array<std::uint8_t, 4096> data{};
std::size_t room, pending;
{
std::lock_guard lock(mutex);
// One PTY read can expand into a screen redraw. Drain that redraw
// in order before consuming more output, even after shell exit.
auto transfer = std::min(display.size() - displayOffset, queueLimit - incoming.size());
incoming.insert(incoming.end(), display.begin() + displayOffset,
display.begin() + displayOffset + transfer);
displayOffset += transfer;
room = displayOffset == display.size() && incoming.size() < queueLimit ? data.size() : 0;
pending = std::min(data.size(), outgoing.size());
}
if (!reaped) {
pid_t result = ::waitpid(child.pid, nullptr, WNOHANG);
reaped = result == child.pid || (result < 0 && errno == ECHILD);
}
pollfd descriptor{child.master, short((room ? POLLIN : 0) | (pending ? POLLOUT : 0)), 0};
if (!room && !pending) { std::this_thread::sleep_for(10ms); continue; }
int result = ::poll(&descriptor, 1, 10);
if (result < 0 && errno == EINTR) continue;
if (result < 0) break;
if (pending && (descriptor.revents & POLLOUT)) {
std::lock_guard lock(mutex);
if (stopped) break;
std::copy_n(outgoing.begin(), pending, data.begin());
auto sent = ::write(child.master, data.data(), pending); // non-blocking PTY
if (sent > 0) outgoing.erase(outgoing.begin(), outgoing.begin() + sent);
else if (sent < 0 && errno != EINTR && errno != EAGAIN) break;
}
if (room && (descriptor.revents & (POLLIN | POLLHUP | POLLERR))) {
auto n = ::read(child.master, data.data(), room);
if (n > 0) {
display = terminal.consume(data.data(), static_cast<std::size_t>(n));
displayOffset = 0;
auto replies = terminal.takeReply();
std::lock_guard lock(mutex);
applicationKeys = terminal.applicationCursor();
if (stopped || replies.size() > queueLimit - outgoing.size()) break;
outgoing.insert(outgoing.end(), replies.begin(), replies.end());
continue; // collect any final output before reporting EOF
}
if (n < 0 && errno == EINTR) continue;
if (n <= 0 && (n == 0 || errno != EAGAIN || reaped)) break;
}
if (reaped && room) break;
}
if (!reaped) hangup(child);
state = State::closed;
}
private:
std::mutex mutex;
std::deque<std::uint8_t> incoming, outgoing;
bool applicationKeys = false; // guarded by mutex
};
class ShellChannel final : public Transport {
public:
explicit ShellChannel(std::shared_ptr<Terminal> terminal) : terminal(std::move(terminal)) {}
~ShellChannel() override { terminal->cancel(); }
State state() override { return terminal->transportState(); }
std::size_t read(std::uint8_t* bytes, std::size_t count) override { return terminal->read(bytes, count); }
bool write(const std::uint8_t* bytes, std::size_t count) override { return terminal->write(bytes, count); }
private:
std::shared_ptr<Terminal> terminal;
};
}
struct DriveWireShell::Impl {
explicit Impl(StartupFiles startup) : startup(startup) {}
StartupFiles startup;
mutable std::mutex mutex;
std::chrono::steady_clock::time_point readyUntil{};
std::weak_ptr<Terminal> active;
std::uint64_t sequence = 0, pendingID = 0;
void clear() {
readyUntil = {};
pendingID = 0;
if (auto current = active.lock()) current->cancel();
active.reset();
}
void start(const std::shared_ptr<Terminal>& live) {
live->launched = true;
try {
std::thread([live, files = startup]{ live->run(files); }).detach();
} catch (const std::system_error&) {
live->state = State::failed;
}
}
};
DriveWireShell::DriveWireShell(StartupFiles files) : impl(std::make_unique<Impl>(files)) {}
DriveWireShell::~DriveWireShell() { stop(); }
void DriveWireShell::arm() {
std::lock_guard lock(impl->mutex);
impl->clear();
impl->readyUntil = std::chrono::steady_clock::now() + 2min;
}
void DriveWireShell::stop() {
std::lock_guard lock(impl->mutex);
impl->clear();
}
std::string DriveWireShell::status() const {
std::lock_guard lock(impl->mutex);
if (std::chrono::steady_clock::now() < impl->readyUntil) return "ready";
if (auto live = impl->active.lock()) {
if (live->waiting()) return "requested";
auto state = live->transportState();
if (state == State::connecting || state == State::connected) return "connected";
}
return "idle";
}
std::uint64_t DriveWireShell::requestID() const {
std::lock_guard lock(impl->mutex);
auto live = impl->active.lock();
return live && live->waiting() ? impl->pendingID : 0;
}
bool DriveWireShell::decide(std::uint64_t id, bool allow) {
std::lock_guard lock(impl->mutex);
auto live = impl->active.lock();
if (!id || id != impl->pendingID || !live || !live->waiting()) return false;
impl->pendingID = 0;
if (allow) impl->start(live);
else live->state = State::failed;
return true;
}
std::unique_ptr<Transport> DriveWireShell::connect() {
std::lock_guard lock(impl->mutex);
if (auto live = impl->active.lock()) {
auto state = live->transportState();
if (state == State::connecting || state == State::connected) return {};
}
auto live = std::make_shared<Terminal>();
auto channel = std::make_unique<ShellChannel>(live);
impl->active = live;
if (std::chrono::steady_clock::now() < impl->readyUntil) {
impl->readyUntil = {};
impl->pendingID = 0;
impl->start(live);
} else {
if (!++impl->sequence) ++impl->sequence;
impl->pendingID = impl->sequence;
}
return channel;
}
}