Files
hrynco-kswitcher/src/files_ssh_terminal.inl
T

165 lines
5.8 KiB
C++

std::string sshShellQuote(std::string_view text)
{
std::string quoted="'";
for(const auto character:text)
if(character=='\'') quoted+="'\\''";
else quoted+=character;
return quoted+"'";
}
std::string sshChangeDirectory(const fs::path &path)
{
return "cd "+sshShellQuote(ks::utf8(ftpPath(path)));
}
class FilesSshTerminal
{
std::mutex mutex_;
std::string input_,output_;
std::wstring error_;
COORD size_{};
std::atomic_bool running_{};
std::jthread worker_;
void run(const TransferProfile &profile,const fs::path &directory,const std::string &token,
COORD terminalSize,std::stop_token stop)
{
SshConnection connection(profile);
if(stop.stop_requested()) return;
SshChannel channel(libssh2_channel_open_session(connection.session()),libssh2_channel_free);
if(!channel) connection.operationError("Could not open the SSH terminal");
if(libssh2_channel_request_pty_ex(channel.get(),"xterm-256color",14,nullptr,0,
terminalSize.X,terminalSize.Y,0,0)) connection.operationError("Could not allocate the SSH terminal");
// Expand the prompt after every command so panel navigation can follow even scripted directory changes.
const auto report="printf '\\033]633;ks-ssh-dir:"+token+
":%s\\007' \"$(printf '%s' \"$(pwd -P)\" | base64 | tr -d '\\r\\n')\"";
const auto command=sshChangeDirectory(directory)+
" || exit; command -v base64 >/dev/null 2>&1 || { echo 'SSH directory sync requires base64.'; exit 1; }; "
"if command -v bash >/dev/null 2>&1; then exec env PS1='' PS2='> ' PROMPT_COMMAND="+
sshShellQuote(report)+" bash --noprofile --norc -i; else exec env ENV=/dev/null PS2='> ' PS1="+
sshShellQuote("$("+report+")")+" /bin/sh -i; fi";
if(libssh2_channel_exec(channel.get(),command.c_str()))
connection.operationError("Could not start the SSH shell");
connection.nonblocking();
auto buffer=std::array<char,32768>{};
std::string pending;
size_t offset{};
std::optional<COORD> resize;
while(!stop.stop_requested())
{
{
const std::lock_guard lock(mutex_);
if(pending.empty()) pending.swap(input_);
if(!resize && (terminalSize.X!=size_.X || terminalSize.Y!=size_.Y)) resize=size_;
}
bool progressed=false;
if(resize)
{
const auto result=libssh2_channel_request_pty_size(channel.get(),resize->X,resize->Y);
if(result!=LIBSSH2_ERROR_EAGAIN)
{
terminalSize=*resize;
resize.reset();
}
}
if(!pending.empty())
{
const auto count=libssh2_channel_write(channel.get(),pending.data()+offset,pending.size()-offset);
if(count<0 && count!=LIBSSH2_ERROR_EAGAIN) connection.operationError("Could not send SSH terminal input");
if(count>0)
{
offset+=count;
if(offset==pending.size()) {pending.clear();offset=0;}
progressed=true;
}
}
for(int stream:{0,SSH_EXTENDED_DATA_STDERR})
{
const auto count=libssh2_channel_read_ex(channel.get(),stream,buffer.data(),buffer.size());
if(count<0 && count!=LIBSSH2_ERROR_EAGAIN) connection.operationError("Could not read SSH terminal output");
if(count>0)
{
const std::lock_guard lock(mutex_);
output_.append(buffer.data(),count);
constexpr size_t limit=1024*1024;
if(output_.size()>limit) output_.erase(0,output_.size()-limit);
progressed=true;
}
}
if(!progressed)
{
if(libssh2_channel_eof(channel.get())) break;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
// The connection owns all channels. Its teardown also handles a channel blocked in a nonblocking request.
channel.release();
}
public:
bool running() const {return running_;}
void start(TransferProfile profile,fs::path directory,std::string token,COORD size)
{
{
const std::lock_guard lock(mutex_);
input_.clear();
output_.clear();
error_.clear();
size_=size;
}
running_=true;
try
{
worker_=std::jthread([this,profile=std::move(profile),directory=std::move(directory),
token=std::move(token),size](std::stop_token stop)
{
try {run(profile,directory,token,size,stop);}
catch(const std::exception &error)
{
const std::lock_guard lock(mutex_);
error_=ks::wide(error.what());
}
running_=false;
});
}
catch(...)
{
running_=false;
throw;
}
}
void stop() {worker_.request_stop();}
bool write(std::string_view input)
{
if(!running_) return false;
const std::lock_guard lock(mutex_);
constexpr size_t limit=256*1024;
if(input.size()>limit-input_.size()) return false;
input_+=input;
return true;
}
void resize(COORD size)
{
const std::lock_guard lock(mutex_);
size_=size;
}
std::string takeOutput()
{
const std::lock_guard lock(mutex_);
return std::exchange(output_,{});
}
std::wstring takeError()
{
const std::lock_guard lock(mutex_);
return std::exchange(error_,{});
}
};