Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ef30ab5e8 | ||
|
|
6279a2ee4f |
No files matched your search
+14
@@ -77,6 +77,20 @@ Warning і початковий фокус на No.
|
||||
Files блокує підключення до передачі пароля або підпису.
|
||||
Для запланованої заміни ключа використовуй **Forget host key**,
|
||||
а тоді **Test connection** зі звіркою нового відбитка.
|
||||
- **Jump via** у SFTP-профілі вибирає попередній збережений SSH-профіль
|
||||
у маршруті. **Direct** підключається напряму. Профіль-посередник може
|
||||
мати власний **Jump via**. Кожен хост має окремий довірений ключ і
|
||||
перевіряється до входу. Маршрут підтримує до восьми хостів і перевіряється
|
||||
на цикли під час збереження. Профіль без доступу до SFTP можна
|
||||
використовувати для пересилання через SSH.
|
||||
- На підключеній SFTP-панелі Ctrl+O відкриває інтерактивну SSH-сесію.
|
||||
Enter після введення команди запускає ту саму сесію з командного рядка.
|
||||
Після `cd` успішно відкритий каталог відображається в панелі.
|
||||
Зміна каталогу в панелі також оновлює робочу папку сесії.
|
||||
Поки команда працює, термінал приймає її інтерактивне введення, зокрема
|
||||
Ctrl+C. При переході до іншої панелі чи джерела сесія від'єднується.
|
||||
Для синхронізації потрібні POSIX-оболонка й утиліта `base64` на сервері.
|
||||
Оболонка та SFTP мають бачити однакові абсолютні шляхи.
|
||||
- Для SFTP використовуються ключі хоста ECDSA або RSA з підписом SHA‑2.
|
||||
F3 і F4 відкривають Viewer та Editor. F2 в Editor перевіряє розмір і час
|
||||
зміни віддаленого файла перед збереженням. F5 копіює між локальною
|
||||
|
||||
+3
-1
@@ -577,7 +577,9 @@ BEGIN
|
||||
EDITTEXT 390, 210, 96, 194, 15, ES_LEFT | ES_PASSWORD | ES_AUTOHSCROLL
|
||||
LTEXT "Private &key file (optional)", 562, 16, 117, 388, 12
|
||||
FAR_EDIT(563, 0, 16, 130, 388, 15)
|
||||
LTEXT "", 566, 16, 153, 388, 14, SS_ENDELLIPSIS | SS_NOPREFIX
|
||||
LTEXT "", 566, 16, 153, 218, 14, SS_ENDELLIPSIS | SS_NOPREFIX
|
||||
LTEXT "&Jump via", 568, 240, 153, 56, 14
|
||||
COMBOBOX 567, 298, 150, 106, 90, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
LTEXT "", 391, 10, 175, 1, 1, NOT WS_VISIBLE
|
||||
CONTROL "&Test connection", 564, "Button", BS_OWNERDRAW | WS_TABSTOP, 20, 183, 128, 17
|
||||
CONTROL "&Forget host key", 565, "Button", BS_OWNERDRAW | WS_TABSTOP, 152, 183, 112, 17
|
||||
|
||||
@@ -9,6 +9,10 @@ const terminal = new Terminal({
|
||||
const fit = new FitAddon.FitAddon();
|
||||
terminal.parser.registerOscHandler(633, data => {
|
||||
const prefix = 'ks-directory:';
|
||||
if (data.startsWith('ks-ssh-dir:')) {
|
||||
bridge.postMessage('ssh-directory:' + data.slice(11));
|
||||
return true;
|
||||
}
|
||||
if (!data.startsWith(prefix)) return false;
|
||||
try {
|
||||
bridge.postMessage('directory:' + decodeURIComponent(data.slice(prefix.length)));
|
||||
@@ -22,9 +26,13 @@ const host = document.getElementById('terminal');
|
||||
terminal.open(host);
|
||||
terminal.onSelectionChange(() => bridge.postMessage('selection:' + terminal.getSelection()));
|
||||
const prompt = message => bridge.postMessage('prompt:' + message);
|
||||
host.addEventListener('pointerup', () => prompt('focus-input'), true);
|
||||
let sshInput = false;
|
||||
host.addEventListener('pointerup', () => {
|
||||
if (!sshInput) prompt('focus-input');
|
||||
}, true);
|
||||
terminal.onData(text => {
|
||||
if (!/[\x00-\x1f\x7f]/u.test(text)) prompt('text:' + text);
|
||||
if (sshInput) bridge.postMessage('ssh-input:' + text);
|
||||
else if (!/[\x00-\x1f\x7f]/u.test(text)) prompt('text:' + text);
|
||||
});
|
||||
const screen = host.querySelector('.xterm-screen');
|
||||
let traceEnabled = false;
|
||||
@@ -61,6 +69,14 @@ const promptKeys = new Set([
|
||||
]);
|
||||
terminal.attachCustomKeyEventHandler(event => {
|
||||
if (event.isComposing) return true;
|
||||
if (sshInput) {
|
||||
if (event.type !== 'keydown' || !event.ctrlKey || event.altKey || event.metaKey) return true;
|
||||
const copy = event.code === 'KeyC' && terminal.hasSelection();
|
||||
if (!copy && (event.shiftKey || event.code !== 'KeyO')) return true;
|
||||
event.preventDefault();
|
||||
if (!event.repeat) bridge.postMessage(copy ? 'copy-command-line' : 'toggle');
|
||||
return false;
|
||||
}
|
||||
if (event.type === 'keydown' && promptKeys.has(event.key) &&
|
||||
!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {
|
||||
prompt(event.key);
|
||||
@@ -99,6 +115,21 @@ terminal.onScroll(() => {
|
||||
anchorOutput();
|
||||
});
|
||||
bridge.addEventListener('message', ({ data }) => {
|
||||
if (data === 'ssh-input:on' || data === 'ssh-input:off') {
|
||||
sshInput = data === 'ssh-input:on';
|
||||
terminal.options.cursorBlink = sshInput;
|
||||
terminal.write(sshInput ? '\x1b[?25h' : '\x1b[?25l');
|
||||
return;
|
||||
}
|
||||
if (data === 'ssh-focus') {
|
||||
terminal.focus();
|
||||
return;
|
||||
}
|
||||
if (data === 'ssh-reset') {
|
||||
terminal.reset();
|
||||
terminal.write('\x1b[?25l');
|
||||
return;
|
||||
}
|
||||
if (data === 'clear-selection') {
|
||||
terminal.clearSelection();
|
||||
return;
|
||||
|
||||
+35
-3
@@ -16,6 +16,7 @@ struct TransferProfile
|
||||
TransferProtocol protocol{};
|
||||
fs::path privateKey;
|
||||
std::string hostFingerprint;
|
||||
std::string jumpProfile;
|
||||
};
|
||||
|
||||
struct TransferProfiles
|
||||
@@ -31,6 +32,29 @@ TransferProfiles &transferProfiles(TransferProtocol protocol)
|
||||
return protocol==TransferProtocol::sftp?sftp:ftp;
|
||||
}
|
||||
|
||||
std::atomic<std::shared_ptr<const std::vector<TransferProfile>>> sshProfiles;
|
||||
|
||||
constexpr size_t sshRouteLimit=8;
|
||||
|
||||
std::vector<TransferProfile> sshRoute(const TransferProfile &destination,
|
||||
const std::vector<TransferProfile> &profiles)
|
||||
{
|
||||
std::vector<TransferProfile> route{destination};
|
||||
std::set<std::string> seen{destination.id};
|
||||
while(!route.back().jumpProfile.empty())
|
||||
{
|
||||
const auto &id=route.back().jumpProfile;
|
||||
if(!seen.insert(id).second) throw std::runtime_error("The SSH jump route contains a loop.");
|
||||
if(route.size()>=sshRouteLimit) throw std::runtime_error("An SSH route can contain up to eight hosts.");
|
||||
const auto hop=std::find_if(profiles.begin(),profiles.end(),
|
||||
[&id](const auto &profile){return profile.id==id;});
|
||||
if(hop==profiles.end()) throw std::runtime_error("An SSH jump profile is missing. Edit this connection to update its route.");
|
||||
route.push_back(*hop);
|
||||
}
|
||||
std::reverse(route.begin(),route.end());
|
||||
return route;
|
||||
}
|
||||
|
||||
constexpr DWORD transferProfilesMaxBytes=1024*1024;
|
||||
const fs::path ftpRoot=L"\\";
|
||||
|
||||
@@ -58,13 +82,18 @@ bool saveTransferProfiles(TransferProtocol protocol,const std::vector<TransferPr
|
||||
{
|
||||
row["privateKey"]=ks::utf8(profile.privateKey.native());
|
||||
row["hostFingerprint"]=profile.hostFingerprint;
|
||||
row["jumpProfile"]=profile.jumpProfile;
|
||||
}
|
||||
rows.push_back(std::move(row));
|
||||
}
|
||||
const auto data=rows.dump();
|
||||
return data.size()<=transferProfilesMaxBytes &&
|
||||
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,transferProfiles(protocol).preference,REG_BINARY,data.data(),
|
||||
static_cast<DWORD>(data.size()))==ERROR_SUCCESS;
|
||||
if(data.size()>transferProfilesMaxBytes) return false;
|
||||
const auto snapshot=protocol==TransferProtocol::sftp?
|
||||
std::make_shared<const std::vector<TransferProfile>>(profiles):nullptr;
|
||||
if(RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,transferProfiles(protocol).preference,REG_BINARY,data.data(),
|
||||
static_cast<DWORD>(data.size()))!=ERROR_SUCCESS) return false;
|
||||
if(snapshot) sshProfiles=snapshot;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool loadTransferProfiles(TransferProtocol protocol=TransferProtocol::ftp)
|
||||
@@ -101,9 +130,12 @@ bool loadTransferProfiles(TransferProtocol protocol=TransferProtocol::ftp)
|
||||
{
|
||||
profile.privateKey=ks::wide(row.value("privateKey",std::string{}));
|
||||
profile.hostFingerprint=row.value("hostFingerprint",std::string{});
|
||||
profile.jumpProfile=row.value("jumpProfile",std::string{});
|
||||
}
|
||||
profiles.push_back(std::move(profile));
|
||||
}
|
||||
if(protocol==TransferProtocol::sftp)
|
||||
sshProfiles=std::make_shared<const std::vector<TransferProfile>>(profiles);
|
||||
settings.rows=std::move(profiles);
|
||||
settings.loaded=true;
|
||||
return true;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
namespace transferDialog
|
||||
{
|
||||
constexpr int name=382, host=385, port=386, user=388, password=390, footer=391, legacy=392;
|
||||
constexpr int keyLabel=562,keyFile=563,testConnection=564,forgetKey=565,hostStatus=566;
|
||||
constexpr int keyLabel=562,keyFile=563,testConnection=564,forgetKey=565,hostStatus=566,jumpVia=567,jumpLabel=568;
|
||||
|
||||
struct Edit
|
||||
{
|
||||
@@ -10,6 +10,7 @@ struct Edit
|
||||
std::wstring pinnedHost;
|
||||
INTERNET_PORT pinnedPort{};
|
||||
std::string pin;
|
||||
std::vector<std::string> jumpChoices;
|
||||
bool testing{};
|
||||
std::atomic_bool canceled{};
|
||||
};
|
||||
@@ -37,6 +38,23 @@ void showHostStatus(HWND dialog,const Edit &edit)
|
||||
EnableWindow(GetDlgItem(dialog,forgetKey),trusted && !edit.testing);
|
||||
}
|
||||
|
||||
void addJumpChoice(HWND dialog,Edit &edit,const std::wstring &label,const std::string &id)
|
||||
{
|
||||
const auto row=SendDlgItemMessageW(dialog,jumpVia,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
|
||||
if(row==CB_ERR || row==CB_ERRSPACE) return;
|
||||
edit.jumpChoices.push_back(id);
|
||||
if(id==edit.profile.jumpProfile) SendDlgItemMessageW(dialog,jumpVia,CB_SETCURSEL,row,0);
|
||||
}
|
||||
|
||||
void populateJumpChoices(HWND dialog,Edit &edit)
|
||||
{
|
||||
addJumpChoice(dialog,edit,L"Direct",{});
|
||||
for(const auto &profile:transferProfiles(TransferProtocol::sftp).rows)
|
||||
if(profile.id!=edit.profile.id) addJumpChoice(dialog,edit,profile.name,profile.id);
|
||||
if(SendDlgItemMessageW(dialog,jumpVia,CB_GETCURSEL,0,0)==CB_ERR)
|
||||
addJumpChoice(dialog,edit,L"Missing profile",edit.profile.jumpProfile);
|
||||
}
|
||||
|
||||
std::optional<TransferProfile> readProfile(HWND dialog,const Edit &edit)
|
||||
{
|
||||
TransferProfile profile;
|
||||
@@ -48,6 +66,7 @@ std::optional<TransferProfile> readProfile(HWND dialog,const Edit &edit)
|
||||
SetFocus(GetDlgItem(dialog,field));
|
||||
return {};
|
||||
};
|
||||
profile.id=edit.index?edit.profile.id:ks::lan::randomHex(16);
|
||||
profile.legacyNames=!sftp && IsDlgButtonChecked(dialog,legacy)==BST_CHECKED;
|
||||
profile.name=trimFilesField(shortcutField(dialog,name));
|
||||
if(profile.name.empty() || profile.name==L".." || profile.name.find_first_of(L"\r\n\t")!=profile.name.npos)
|
||||
@@ -72,6 +91,14 @@ std::optional<TransferProfile> readProfile(HWND dialog,const Edit &edit)
|
||||
if(!profile.privateKey.empty() && !profile.privateKey.is_absolute())
|
||||
return invalid(keyFile,L"Enter the full path of the private key file.");
|
||||
if(sameEndpoint(edit,profile)) profile.hostFingerprint=edit.pin;
|
||||
const auto choice=SendDlgItemMessageW(dialog,jumpVia,CB_GETCURSEL,0,0);
|
||||
if(choice>=0 && static_cast<size_t>(choice)<edit.jumpChoices.size())
|
||||
profile.jumpProfile=edit.jumpChoices[choice];
|
||||
try {sshRoute(profile,profiles);}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
return invalid(jumpVia,ks::wide(error.what()).c_str());
|
||||
}
|
||||
}
|
||||
auto plain=shortcutField(dialog,password);
|
||||
if(!plain.empty())
|
||||
@@ -90,14 +117,13 @@ std::optional<TransferProfile> readProfile(HWND dialog,const Edit &edit)
|
||||
} erase{bytes,plain};
|
||||
profile.secret=ks::protect(bytes);
|
||||
}
|
||||
profile.id=edit.index?edit.profile.id:ks::lan::randomHex(16);
|
||||
return profile;
|
||||
}
|
||||
|
||||
template<class Task>
|
||||
bool runTest(HWND dialog,Edit &edit,const wchar_t *status,Task task)
|
||||
{
|
||||
constexpr int controls[]{name,host,port,user,password,keyFile,testConnection,forgetKey,IDOK};
|
||||
constexpr int controls[]{name,host,port,user,password,keyFile,jumpVia,testConnection,forgetKey,IDOK};
|
||||
edit.testing=true;
|
||||
edit.canceled=false;
|
||||
for(const auto id:controls) EnableWindow(GetDlgItem(dialog,id),FALSE);
|
||||
@@ -125,7 +151,7 @@ void testSftp(HWND dialog,Edit &edit,TransferProfile profile)
|
||||
{
|
||||
std::string fingerprint;
|
||||
if(!runTest(dialog,edit,L"Reading the SSH host key…",[&] {
|
||||
const SftpSession probe(profile,true);
|
||||
const SshConnection probe(profile,true);
|
||||
fingerprint=probe.fingerprint();
|
||||
})) return;
|
||||
const auto prompt=profile.host+L":"+std::to_wstring(profile.port)+L"\r\n"+ks::wide(fingerprint)+
|
||||
@@ -136,12 +162,15 @@ void testSftp(HWND dialog,Edit &edit,TransferProfile profile)
|
||||
profile.hostFingerprint=edit.pin=std::move(fingerprint);
|
||||
}
|
||||
fs::path initial;
|
||||
if(runTest(dialog,edit,L"Testing the SFTP login…",[&] {
|
||||
SftpSession session(profile);
|
||||
initial=session.initialDirectory();
|
||||
if(runTest(dialog,edit,L"Testing the SSH login…",[&] {
|
||||
SshConnection connection(profile);
|
||||
const SftpSubsystem sftp(libssh2_sftp_init(connection.session()),libssh2_sftp_shutdown);
|
||||
if(sftp) initial=sftpInitialDirectory(sftp.get());
|
||||
}))
|
||||
{
|
||||
const auto details=L"Connected to "+profile.host+L".\r\n\r\nInitial folder "+ftpPath(initial)+L".";
|
||||
const auto details=L"Connected to "+profile.host+L".\r\n\r\n"+(initial.empty()?
|
||||
L"SFTP is unavailable. This profile can still be used as an SSH jump host.":
|
||||
L"Initial folder "+ftpPath(initial)+L".");
|
||||
showFilesNotice(dialog,details.c_str(),L"SFTP connection test");
|
||||
}
|
||||
}
|
||||
@@ -159,7 +188,7 @@ INT_PTR CALLBACK procedure(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
const auto &profile=edit->profile;
|
||||
prepareCopyDialog(dialog);
|
||||
layoutDialogContent(dialog,381);
|
||||
for(const auto id:{381,383,384,387,389,legacy,IDOK,IDCANCEL,keyLabel,hostStatus})
|
||||
for(const auto id:{381,383,384,387,389,legacy,IDOK,IDCANCEL,keyLabel,hostStatus,jumpVia,jumpLabel})
|
||||
if(const auto control=GetDlgItem(dialog,id)) SendMessageW(control,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
|
||||
for(const auto id:{name,host,user,password})
|
||||
SendDlgItemMessageW(dialog,id,EM_SETLIMITTEXT,255,0);
|
||||
@@ -172,6 +201,8 @@ INT_PTR CALLBACK procedure(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
SendDlgItemMessageW(dialog,keyFile,EM_SETLIMITTEXT,32767,0);
|
||||
SetDlgItemTextW(dialog,keyFile,profile.privateKey.c_str());
|
||||
populateJumpChoices(dialog,*edit);
|
||||
installFarCombo(GetDlgItem(dialog,jumpVia),GetDlgItem(dialog,keyFile));
|
||||
showHostStatus(dialog,*edit);
|
||||
layoutDialogButtons(dialog,footer,{testConnection,forgetKey,IDOK,IDCANCEL});
|
||||
}
|
||||
|
||||
+95
-25
@@ -373,6 +373,7 @@ constexpr auto schemeKey = L"Software\\KSwitcher\\Files";
|
||||
#include "files_registry_json.inl"
|
||||
#include "files_ftp.inl"
|
||||
#include "files_sftp.inl"
|
||||
#include "files_ssh_terminal.inl"
|
||||
#include "files_transfer.inl"
|
||||
|
||||
|
||||
@@ -739,7 +740,22 @@ void traceTerminal(const char *event,int a=0,int b=0,int c=0,int d=0,int e=0)
|
||||
++terminalTraceLines;
|
||||
terminalTrace<<GetTickCount64()<<' '<<event<<' '<<a<<' '<<b<<' '<<c<<' '<<d<<' '<<e<<std::endl;
|
||||
}
|
||||
FilesTerminalView terminalView;
|
||||
FilesTerminalView terminalView,sshView;
|
||||
FilesSshTerminal sshTerminal;
|
||||
struct SshPrompt
|
||||
{
|
||||
int panel{};
|
||||
std::string profile,token;
|
||||
fs::path panelDirectory,shellDirectory;
|
||||
std::optional<std::wstring> startupCommand;
|
||||
bool waiting=true;
|
||||
bool raw{},finished{};
|
||||
};
|
||||
std::optional<SshPrompt> sshPrompt;
|
||||
COORD sshSize{80,25};
|
||||
bool sshViewRequested{};
|
||||
|
||||
FilesTerminalView &activeTerminalView(){return sshPrompt?sshView:terminalView;}
|
||||
std::wstring terminalSelection;
|
||||
COORD terminalSize{80,25};
|
||||
bool terminalViewRequested{};
|
||||
@@ -1162,6 +1178,7 @@ bool applyFont(HWND owner, LOGFONTW font, int points)
|
||||
displayFont=font;
|
||||
fontPoints=points;
|
||||
terminalView.setFont(displayFont,fontPoints);
|
||||
sshView.setFont(displayFont,fontPoints);
|
||||
for(auto &panel:panels)
|
||||
{
|
||||
if(panel.path) SendMessageW(panel.path,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
|
||||
@@ -1533,6 +1550,7 @@ void swapPanels(HWND window)
|
||||
std::swap(panels[0],panels[1]);
|
||||
active=1-active;
|
||||
if(quickViewWindow) quickViewSource=1-quickViewSource;
|
||||
if(sshPrompt) sshPrompt->panel=1-sshPrompt->panel;
|
||||
for(auto &command:terminalCommands)
|
||||
if(command.panel>=0) command.panel=1-command.panel;
|
||||
for(int i=0;i<2;++i)
|
||||
@@ -1652,7 +1670,8 @@ void layout(HWND window,bool activeOnly)
|
||||
if(!showOutput) clearTerminalSelection();
|
||||
ShowWindow(terminalOutput,showOutput?SW_SHOWNA:SW_HIDE);
|
||||
ShowWindow(status,terminalVisible?SW_HIDE:SW_SHOWNA);
|
||||
terminalView.layout(terminalOutput,showOutput,terminalBottom-4);
|
||||
terminalView.layout(terminalOutput,showOutput && !sshPrompt,terminalBottom-4);
|
||||
sshView.layout(terminalOutput,showOutput && sshPrompt.has_value(),terminalBottom-4);
|
||||
constexpr int refreshExtra=4;
|
||||
for (int i = 0; i < static_cast<int>(std::size(commands)); ++i)
|
||||
{
|
||||
@@ -1717,7 +1736,12 @@ void showTerminal(HWND owner,bool show)
|
||||
{
|
||||
terminalVisible=show;
|
||||
layout(owner);
|
||||
SetFocus(terminalInput);
|
||||
if(show && sshPrompt && sshPrompt->raw)
|
||||
{
|
||||
sshView.focus();
|
||||
sshView.post(L"ssh-focus");
|
||||
}
|
||||
else SetFocus(terminalInput);
|
||||
}
|
||||
|
||||
void open(Panel &panel,const fs::path &directory,bool offerElevation);
|
||||
@@ -2044,7 +2068,7 @@ void clearTerminalSelection()
|
||||
{
|
||||
if(terminalSelection.empty()) return;
|
||||
terminalSelection.clear();
|
||||
terminalView.post(L"clear-selection");
|
||||
activeTerminalView().post(L"clear-selection");
|
||||
}
|
||||
|
||||
bool copyFilesText(HWND owner,const std::wstring &value,const wchar_t *failure)
|
||||
@@ -2056,6 +2080,8 @@ bool copyFilesText(HWND owner,const std::wstring &value,const wchar_t *failure)
|
||||
|
||||
bool interruptTerminal()
|
||||
{
|
||||
if(sshPrompt)
|
||||
return sshPrompt->raw && sshTerminal.write("\x03");
|
||||
if(remoteCommandRunning)
|
||||
{
|
||||
remoteCommandThread.request_stop();
|
||||
@@ -2260,16 +2286,22 @@ void handleTerminalPromptInput(HWND owner,std::wstring_view action)
|
||||
SendMessageW(terminalInput,character?WM_CHAR:WM_KEYDOWN,key->second,0);
|
||||
}
|
||||
|
||||
bool ensureTerminalView(HWND owner)
|
||||
void acceptSshDirectory(HWND owner,std::wstring_view message);
|
||||
|
||||
bool ensureTerminalView(HWND owner,bool ssh=false)
|
||||
{
|
||||
if(!terminalViewRequested)
|
||||
auto &view=ssh?sshView:terminalView;
|
||||
auto &requested=ssh?sshViewRequested:terminalViewRequested;
|
||||
if(!requested)
|
||||
{
|
||||
terminalViewRequested=terminalView.create(terminalOutput,[owner](const std::wstring &message)
|
||||
requested=view.create(terminalOutput,[owner,ssh](const std::wstring &message)
|
||||
{
|
||||
auto &source=ssh?sshView:terminalView;
|
||||
if(message==L"ready")
|
||||
{
|
||||
terminalView.setFont(displayFont,fontPoints);
|
||||
if(terminalTrace.is_open()) terminalView.enableTrace(traceTerminalOutput);
|
||||
source.setFont(displayFont,fontPoints);
|
||||
if(ssh) source.post(L"ssh-reset");
|
||||
if(terminalTrace.is_open() && !ssh) source.enableTrace(traceTerminalOutput);
|
||||
}
|
||||
else if(traceTerminalOutput && terminalTrace.is_open() && message.starts_with(L"output:"))
|
||||
terminalTrace<<"output "<<ks::utf8(message.substr(7))<<std::endl;
|
||||
@@ -2283,7 +2315,14 @@ bool ensureTerminalView(HWND owner)
|
||||
traceTerminal(events[phase],height,rows,viewport,base,offset);
|
||||
}
|
||||
}
|
||||
else if(message.starts_with(L"directory:"))
|
||||
else if(ssh && message.starts_with(L"ssh-directory:"))
|
||||
acceptSshDirectory(owner,std::wstring_view(message).substr(14));
|
||||
else if(ssh && message.starts_with(L"ssh-input:"))
|
||||
{
|
||||
if(sshPrompt && sshPrompt->raw && GetForegroundWindow()==owner && commandLineAvailable(owner))
|
||||
sshTerminal.write(ks::utf8(message.substr(10)));
|
||||
}
|
||||
else if(!ssh && message.starts_with(L"directory:"))
|
||||
{
|
||||
const auto directory=message.substr(10);
|
||||
if(!terminalCommands.empty())
|
||||
@@ -2302,8 +2341,14 @@ bool ensureTerminalView(HWND owner)
|
||||
}
|
||||
terminalDirectory=directory;
|
||||
}
|
||||
else if(message.starts_with(L"selection:")) terminalSelection=message.substr(10);
|
||||
else if(message.starts_with(L"prompt:")) handleTerminalPromptInput(owner,std::wstring_view(message).substr(7));
|
||||
else if(message.starts_with(L"selection:"))
|
||||
{
|
||||
if(ssh==sshPrompt.has_value()) terminalSelection=message.substr(10);
|
||||
}
|
||||
else if(message.starts_with(L"prompt:"))
|
||||
{
|
||||
if(ssh==sshPrompt.has_value()) handleTerminalPromptInput(owner,std::wstring_view(message).substr(7));
|
||||
}
|
||||
else if(message==L"insert-path") insertCurrentPanelPath();
|
||||
else if(message==L"insert-name") insertCurrentPanelPath(true);
|
||||
else if(message==L"copy-command-line" && GetForegroundWindow()==owner && commandLineAvailable(owner))
|
||||
@@ -2322,16 +2367,24 @@ bool ensureTerminalView(HWND owner)
|
||||
if(swscanf_s(message.c_str()+5,L"%d,%d",&columns,&rows)==2 &&
|
||||
columns>=2 && columns<=32767 && rows>=2 && rows<=32767)
|
||||
{
|
||||
terminalSize={static_cast<SHORT>(columns),static_cast<SHORT>(rows)};
|
||||
terminal.resize(terminalSize);
|
||||
const COORD size{static_cast<SHORT>(columns),static_cast<SHORT>(rows)};
|
||||
if(ssh) {sshSize=size;sshTerminal.resize(size);}
|
||||
else {terminalSize=size;terminal.resize(size);}
|
||||
}
|
||||
}
|
||||
},[owner]
|
||||
},[owner,ssh]
|
||||
{
|
||||
showTerminal(owner,false);
|
||||
if(ssh)
|
||||
{
|
||||
sshTerminal.stop();
|
||||
sshPrompt.reset();
|
||||
sshViewRequested=false;
|
||||
sshView.close();
|
||||
}
|
||||
if(ssh || !sshPrompt) showTerminal(owner,false);
|
||||
setStatus(L"Could not initialize the terminal view.");
|
||||
});
|
||||
if(!terminalViewRequested)
|
||||
},false,{},ssh);
|
||||
if(!requested)
|
||||
{
|
||||
setStatus(L"WebView2 and the local terminal assets are required.");
|
||||
return false;
|
||||
@@ -2340,8 +2393,11 @@ bool ensureTerminalView(HWND owner)
|
||||
return true;
|
||||
}
|
||||
|
||||
#include "files_ssh_prompt.inl"
|
||||
|
||||
bool startTerminal(HWND owner,const fs::path &directory)
|
||||
{
|
||||
closeSshPrompt(owner);
|
||||
if(terminal.alive()) return true;
|
||||
if(!ensureTerminalView(owner)) return false;
|
||||
if(terminal.start(directory.c_str(),terminalSize))
|
||||
@@ -2356,12 +2412,16 @@ bool startTerminal(HWND owner,const fs::path &directory)
|
||||
|
||||
bool showCommandOutput(HWND owner,const Panel &panel)
|
||||
{
|
||||
if(panel.ftp && panel.ftp->protocol==TransferProtocol::sftp && !panel.ftp->id.empty())
|
||||
return startSshTerminal(owner,panel);
|
||||
closeSshPrompt(owner);
|
||||
if(panel.archive) return startTerminal(owner,panel.archive->file.parent_path());
|
||||
return panel.peer || panel.ftp?ensureTerminalView(owner):startTerminal(owner,panel.directory);
|
||||
}
|
||||
|
||||
void updateTerminalOutput()
|
||||
void updateTerminalOutput(HWND owner)
|
||||
{
|
||||
updateSshTerminal(owner);
|
||||
if(!terminalView.initialized()) return;
|
||||
const auto bytes=terminal.takeOutput();
|
||||
if(!bytes.empty()) terminalView.send(bytes);
|
||||
@@ -2396,9 +2456,12 @@ bool submitTerminalCommand(const Panel &panel,const std::wstring &value)
|
||||
}
|
||||
if(panel.ftp)
|
||||
{
|
||||
setStatus(std::wstring(L"Shell commands are unavailable in ")+transferProtocolName(panel.ftp->protocol)+L" panels.");
|
||||
if(panel.ftp->protocol==TransferProtocol::sftp && !panel.ftp->id.empty())
|
||||
return submitSshCommand(owner,panel,value);
|
||||
setStatus(L"Shell commands require a connected SFTP, LAN or local folder.");
|
||||
return false;
|
||||
}
|
||||
closeSshPrompt(owner);
|
||||
if(remoteCommandRunning)
|
||||
{
|
||||
constexpr auto busy=L"A remote command is running. Clear the command line and press Escape to cancel it.";
|
||||
@@ -2476,7 +2539,7 @@ void runCommandLine()
|
||||
{
|
||||
const auto value=terminalInputText();
|
||||
if(!submitTerminalCommand(panels[active],value)) return;
|
||||
terminalView.post(L"scroll-bottom");
|
||||
activeTerminalView().post(L"scroll-bottom");
|
||||
if(value.find_first_not_of(L" \t\r\n")!=value.npos)
|
||||
{
|
||||
rememberCommand(value);
|
||||
@@ -4927,12 +4990,17 @@ LRESULT CALLBACK paintFarCombo(HWND control,UINT message,WPARAM wp,LPARAM lp,UIN
|
||||
const auto dc=message==WM_PAINT?BeginPaint(control,&paint):reinterpret_cast<HDC>(wp);
|
||||
RECT bounds{};
|
||||
GetClientRect(control,&bounds);
|
||||
wchar_t label[64]{};
|
||||
std::wstring label;
|
||||
const auto selected=SendMessageW(control,CB_GETCURSEL,0,0);
|
||||
if(selected!=CB_ERR) SendMessageW(control,CB_GETLBTEXT,selected,reinterpret_cast<LPARAM>(label));
|
||||
const auto length=selected==CB_ERR?CB_ERR:SendMessageW(control,CB_GETLBTEXTLEN,selected,0);
|
||||
if(length>=0)
|
||||
{
|
||||
label.resize(static_cast<size_t>(length)+1);
|
||||
SendMessageW(control,CB_GETLBTEXT,selected,reinterpret_cast<LPARAM>(label.data()));
|
||||
}
|
||||
const auto parts=farDropDownBounds(bounds);
|
||||
const bool enabled=IsWindowEnabled(control)!=FALSE;
|
||||
paintFarDropDownText(dc,parts.field,label,enabled);
|
||||
paintFarDropDownText(dc,parts.field,label.c_str(),enabled);
|
||||
ks::files::paintFarFieldArrow(dc,parts.arrow,enabled,GetDpiForWindow(control));
|
||||
if(GetFocus()==control) DrawFocusRect(dc,&parts.field);
|
||||
if(message==WM_PAINT) EndPaint(control,&paint);
|
||||
@@ -8020,7 +8088,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
if(pendingPeerAction.valid() &&
|
||||
pendingPeerAction.wait_for(std::chrono::seconds(0))==std::future_status::ready)
|
||||
setStatus(pendingPeerAction.get());
|
||||
updateTerminalOutput();
|
||||
updateTerminalOutput(window);
|
||||
updateCompletion(window);
|
||||
return 0;
|
||||
}
|
||||
@@ -8741,6 +8809,8 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
stopTreeBranches(panel);
|
||||
panel.watch.reset();
|
||||
}
|
||||
sshTerminal.stop();
|
||||
sshView.close();
|
||||
terminalView.close();
|
||||
terminal.close();
|
||||
if(remoteCommandThread.joinable())
|
||||
|
||||
+162
-38
@@ -6,7 +6,7 @@ void initializeSsh()
|
||||
if(initialized) throw std::runtime_error("Could not initialize the SSH client.");
|
||||
}
|
||||
|
||||
void connectSftpSocket(ks::lan::WinSocket &connection,const TransferProfile &profile)
|
||||
void connectSshSocket(ks::lan::WinSocket &connection,const TransferProfile &profile)
|
||||
{
|
||||
ADDRINFOW query{};
|
||||
query.ai_socktype=SOCK_STREAM;
|
||||
@@ -53,28 +53,65 @@ void connectSftpSocket(ks::lan::WinSocket &connection,const TransferProfile &pro
|
||||
throw std::system_error(lastError,std::system_category());
|
||||
}
|
||||
|
||||
struct SftpFile
|
||||
{
|
||||
LIBSSH2_SFTP_HANDLE *handle{};
|
||||
explicit SftpFile(LIBSSH2_SFTP_HANDLE *value):handle(value){}
|
||||
SftpFile(const SftpFile &)=delete;
|
||||
SftpFile(SftpFile &&other) noexcept:handle(std::exchange(other.handle,nullptr)){}
|
||||
~SftpFile(){if(handle) libssh2_sftp_close_handle(handle);}
|
||||
};
|
||||
using SshChannel=std::unique_ptr<LIBSSH2_CHANNEL,decltype(&libssh2_channel_free)>;
|
||||
|
||||
class SftpSession
|
||||
class SshConnection
|
||||
{
|
||||
struct Tunnel
|
||||
{
|
||||
SshChannel channel;
|
||||
LIBSSH2_SESSION *parent;
|
||||
|
||||
struct Nonblocking
|
||||
{
|
||||
LIBSSH2_SESSION *parent;
|
||||
int previous;
|
||||
explicit Nonblocking(LIBSSH2_SESSION *session):
|
||||
parent(session),previous(libssh2_session_get_blocking(parent))
|
||||
{
|
||||
libssh2_session_set_blocking(parent,0);
|
||||
}
|
||||
~Nonblocking(){libssh2_session_set_blocking(parent,previous);}
|
||||
};
|
||||
};
|
||||
|
||||
struct Hop
|
||||
{
|
||||
std::unique_ptr<Tunnel> tunnel;
|
||||
std::unique_ptr<LIBSSH2_SESSION,decltype(&libssh2_session_free)> session{nullptr,libssh2_session_free};
|
||||
};
|
||||
|
||||
ks::lan::Network network_;
|
||||
ks::lan::WinSocket socket_;
|
||||
std::unique_ptr<LIBSSH2_SESSION,decltype(&libssh2_session_free)> session_{nullptr,libssh2_session_free};
|
||||
std::unique_ptr<LIBSSH2_SFTP,decltype(&libssh2_sftp_shutdown)> sftp_{nullptr,libssh2_sftp_shutdown};
|
||||
std::vector<Hop> hops_;
|
||||
std::string fingerprint_;
|
||||
|
||||
static LIBSSH2_SEND_FUNC(sendThroughJump)
|
||||
{
|
||||
const auto &tunnel=*static_cast<Tunnel*>(*abstract);
|
||||
// Channel writes drain incoming packets first. A nested transport must
|
||||
// report when that drain would block so it can still send its own data.
|
||||
const Tunnel::Nonblocking nonblocking(tunnel.parent);
|
||||
const auto result=libssh2_channel_write(tunnel.channel.get(),static_cast<const char*>(buffer),length);
|
||||
return result>=0?result:result==LIBSSH2_ERROR_EAGAIN?-EAGAIN:-EIO;
|
||||
}
|
||||
|
||||
static LIBSSH2_RECV_FUNC(receiveThroughJump)
|
||||
{
|
||||
const auto &tunnel=*static_cast<Tunnel*>(*abstract);
|
||||
const Tunnel::Nonblocking nonblocking(tunnel.parent);
|
||||
auto *channel=tunnel.channel.get();
|
||||
const auto result=libssh2_channel_read(channel,static_cast<char*>(buffer),length);
|
||||
if(result>0) return result;
|
||||
if(result==0 && libssh2_channel_eof(channel)) return 0;
|
||||
return result==0 || result==LIBSSH2_ERROR_EAGAIN?-EAGAIN:-EIO;
|
||||
}
|
||||
|
||||
[[noreturn]] void sshError(const char *operation) const
|
||||
{
|
||||
char *message{};
|
||||
int length{};
|
||||
libssh2_session_last_error(session_.get(),&message,&length,0);
|
||||
libssh2_session_last_error(session(),&message,&length,0);
|
||||
throw std::runtime_error(std::string(operation)+(message && length>0?": "+std::string(message,length):""));
|
||||
}
|
||||
|
||||
@@ -95,7 +132,7 @@ class SftpSession
|
||||
const auto user=ks::utf8(profile.user);
|
||||
int result{};
|
||||
if(profile.privateKey.empty())
|
||||
result=libssh2_userauth_password_ex(session_.get(),user.c_str(),static_cast<unsigned>(user.size()),
|
||||
result=libssh2_userauth_password_ex(session(),user.c_str(),static_cast<unsigned>(user.size()),
|
||||
secret.c_str(),static_cast<unsigned>(secret.size()),nullptr);
|
||||
else
|
||||
{
|
||||
@@ -111,7 +148,7 @@ class SftpSession
|
||||
ks::Bytes publicKey;
|
||||
std::error_code error;
|
||||
if(fs::exists(publicPath,error)) publicKey=ks::readFile(publicPath,64*1024);
|
||||
result=libssh2_userauth_publickey_frommemory(session_.get(),user.c_str(),user.size(),
|
||||
result=libssh2_userauth_publickey_frommemory(session(),user.c_str(),user.size(),
|
||||
publicKey.empty()?nullptr:reinterpret_cast<const char*>(publicKey.data()),publicKey.size(),
|
||||
reinterpret_cast<const char*>(key.data()),key.size(),secret.c_str());
|
||||
}
|
||||
@@ -119,24 +156,36 @@ class SftpSession
|
||||
"SFTP key authentication failed (use RSA PEM without a passphrase, or ECDSA OpenSSH with its .pub file)");
|
||||
}
|
||||
|
||||
static std::string encode(const fs::path &path) {return ks::utf8(ftpPath(path));}
|
||||
|
||||
public:
|
||||
explicit SftpSession(const TransferProfile &profile,bool probeOnly=false)
|
||||
void connectHop(const TransferProfile &profile,bool probeOnly)
|
||||
{
|
||||
if(!probeOnly && profile.hostFingerprint.empty())
|
||||
throw std::runtime_error("The SFTP host key is untrusted. Edit the profile and use Test connection to verify it.");
|
||||
initializeSsh();
|
||||
connectSftpSocket(socket_,profile);
|
||||
session_.reset(libssh2_session_init());
|
||||
if(!session_) throw std::runtime_error("Could not create an SSH session.");
|
||||
libssh2_session_set_timeout(session_.get(),sftpTimeoutMs);
|
||||
libssh2_session_set_read_timeout(session_.get(),sftpTimeoutMs/1000);
|
||||
if(libssh2_session_method_pref(session_.get(),LIBSSH2_METHOD_HOSTKEY,
|
||||
Hop hop;
|
||||
if(hops_.empty()) connectSshSocket(socket_,profile);
|
||||
else
|
||||
{
|
||||
const auto host=ks::utf8(profile.host);
|
||||
SshChannel channel(libssh2_channel_direct_tcpip(session(),host.c_str(),profile.port),libssh2_channel_free);
|
||||
if(!channel) sshError("Could not open an SSH jump tunnel");
|
||||
hop.tunnel=std::make_unique<Tunnel>(Tunnel{std::move(channel),session()});
|
||||
}
|
||||
hop.session.reset(libssh2_session_init_ex(nullptr,nullptr,nullptr,hop.tunnel.get()));
|
||||
if(!hop.session) throw std::runtime_error("Could not create an SSH session.");
|
||||
hops_.push_back(std::move(hop));
|
||||
if(hops_.back().tunnel)
|
||||
{
|
||||
libssh2_session_callback_set2(session(),LIBSSH2_CALLBACK_SEND,
|
||||
reinterpret_cast<libssh2_cb_generic*>(sendThroughJump));
|
||||
libssh2_session_callback_set2(session(),LIBSSH2_CALLBACK_RECV,
|
||||
reinterpret_cast<libssh2_cb_generic*>(receiveThroughJump));
|
||||
}
|
||||
libssh2_session_set_timeout(session(),sftpTimeoutMs);
|
||||
libssh2_session_set_read_timeout(session(),sftpTimeoutMs/1000);
|
||||
if(libssh2_session_method_pref(session(),LIBSSH2_METHOD_HOSTKEY,
|
||||
"ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,rsa-sha2-512,rsa-sha2-256") ||
|
||||
libssh2_session_handshake(session_.get(),socket_.value))
|
||||
libssh2_session_handshake(session(),socket_.value))
|
||||
sshError("Could not negotiate an SSH connection");
|
||||
const auto digest=reinterpret_cast<const BYTE*>(libssh2_hostkey_hash(session_.get(),LIBSSH2_HOSTKEY_HASH_SHA256));
|
||||
const auto digest=reinterpret_cast<const BYTE*>(libssh2_hostkey_hash(session(),LIBSSH2_HOSTKEY_HASH_SHA256));
|
||||
if(!digest) throw std::runtime_error("The server did not provide a verifiable SSH host key.");
|
||||
char fingerprint[64]{};
|
||||
DWORD length=static_cast<DWORD>(std::size(fingerprint));
|
||||
@@ -148,15 +197,93 @@ public:
|
||||
if(!ks::lan::equal(fingerprint_,profile.hostFingerprint))
|
||||
throw std::runtime_error("The SFTP host key changed. Connection blocked before authentication. Received "+fingerprint_+".");
|
||||
authenticate(profile);
|
||||
sftp_.reset(libssh2_sftp_init(session_.get()));
|
||||
if(!sftp_) sshError("Could not start the SFTP subsystem");
|
||||
}
|
||||
|
||||
void close() noexcept
|
||||
{
|
||||
if(socket_.value!=INVALID_SOCKET) shutdown(socket_.value,SD_BOTH);
|
||||
while(!hops_.empty())
|
||||
{
|
||||
auto &hop=hops_.back();
|
||||
libssh2_session_set_blocking(hop.session.get(),1);
|
||||
hop.session.reset();
|
||||
hops_.pop_back();
|
||||
}
|
||||
}
|
||||
|
||||
public:
|
||||
explicit SshConnection(const TransferProfile &destination,bool probeOnly=false)
|
||||
{
|
||||
initializeSsh();
|
||||
const auto profiles=sshProfiles.load();
|
||||
static const std::vector<TransferProfile> empty;
|
||||
const auto route=sshRoute(destination,profiles?*profiles:empty);
|
||||
try
|
||||
{
|
||||
for(size_t i=0;i<route.size();++i)
|
||||
{
|
||||
const auto &profile=route[i];
|
||||
try {connectHop(profile,probeOnly && i+1==route.size());}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
if(route.size()==1) throw;
|
||||
throw std::runtime_error(ks::utf8(profile.name)+": "+error.what());
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(...) {close();throw;}
|
||||
}
|
||||
|
||||
~SshConnection(){close();}
|
||||
LIBSSH2_SESSION *session() const {return hops_.back().session.get();}
|
||||
const std::string &fingerprint() const {return fingerprint_;}
|
||||
|
||||
void nonblocking()
|
||||
{
|
||||
for(const auto &hop:hops_) libssh2_session_set_blocking(hop.session.get(),0);
|
||||
}
|
||||
|
||||
[[noreturn]] void operationError(const char *operation) const {sshError(operation);}
|
||||
};
|
||||
|
||||
struct SftpFile
|
||||
{
|
||||
LIBSSH2_SFTP_HANDLE *handle{};
|
||||
explicit SftpFile(LIBSSH2_SFTP_HANDLE *value):handle(value){}
|
||||
SftpFile(const SftpFile &)=delete;
|
||||
SftpFile(SftpFile &&other) noexcept:handle(std::exchange(other.handle,nullptr)){}
|
||||
~SftpFile(){if(handle) libssh2_sftp_close_handle(handle);}
|
||||
};
|
||||
|
||||
using SftpSubsystem=std::unique_ptr<LIBSSH2_SFTP,decltype(&libssh2_sftp_shutdown)>;
|
||||
|
||||
fs::path sftpInitialDirectory(LIBSSH2_SFTP *sftp)
|
||||
{
|
||||
std::array<char,32768> path{};
|
||||
const auto length=libssh2_sftp_realpath(sftp,".",path.data(),path.size());
|
||||
if(length<=0) return {};
|
||||
auto value=fs::path(ks::wide(std::string(path.data(),length))).lexically_normal();
|
||||
if(!isFtpFolderPath(value)) throw std::runtime_error("The server returned an invalid SFTP folder path.");
|
||||
return value;
|
||||
}
|
||||
|
||||
class SftpSession
|
||||
{
|
||||
SshConnection connection_;
|
||||
SftpSubsystem sftp_{nullptr,libssh2_sftp_shutdown};
|
||||
|
||||
static std::string encode(const fs::path &path) {return ks::utf8(ftpPath(path));}
|
||||
|
||||
public:
|
||||
explicit SftpSession(const TransferProfile &profile):connection_(profile)
|
||||
{
|
||||
sftp_.reset(libssh2_sftp_init(connection_.session()));
|
||||
if(!sftp_) connection_.operationError("Could not start the SFTP subsystem");
|
||||
}
|
||||
|
||||
[[noreturn]] void operationError(const char *operation) const
|
||||
{
|
||||
if(libssh2_session_last_errno(session_.get())==LIBSSH2_ERROR_SFTP_PROTOCOL)
|
||||
if(libssh2_session_last_errno(connection_.session())==LIBSSH2_ERROR_SFTP_PROTOCOL)
|
||||
{
|
||||
const auto status=libssh2_sftp_last_error(sftp_.get());
|
||||
if(status==LIBSSH2_FX_PERMISSION_DENIED)
|
||||
@@ -168,17 +295,14 @@ public:
|
||||
if(status==LIBSSH2_FX_OP_UNSUPPORTED)
|
||||
throw std::system_error(ERROR_NOT_SUPPORTED,std::system_category(),operation);
|
||||
}
|
||||
sshError(operation);
|
||||
connection_.operationError(operation);
|
||||
}
|
||||
|
||||
fs::path initialDirectory() const
|
||||
{
|
||||
std::array<char,32768> path{};
|
||||
const auto length=libssh2_sftp_realpath(sftp_.get(),".",path.data(),path.size());
|
||||
if(length<=0) operationError("Could not resolve the initial SFTP folder");
|
||||
auto value=fs::path(ks::wide(std::string(path.data(),length))).lexically_normal();
|
||||
if(!isFtpFolderPath(value)) throw std::runtime_error("The server returned an invalid SFTP folder path.");
|
||||
return value;
|
||||
auto path=sftpInitialDirectory(sftp_.get());
|
||||
if(path.empty()) operationError("Could not resolve the initial SFTP folder");
|
||||
return path;
|
||||
}
|
||||
|
||||
DWORD list(const fs::path &directory,const FileVisitor &visit,std::stop_token stop={}) const
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
bool panelMatchesSshPrompt()
|
||||
{
|
||||
const auto &panel=panels[active];
|
||||
return sshPrompt && sshPrompt->panel==active && panel.ftp &&
|
||||
panel.ftp->protocol==TransferProtocol::sftp && panel.ftp->id==sshPrompt->profile;
|
||||
}
|
||||
|
||||
void closeSshPrompt(HWND owner)
|
||||
{
|
||||
if(!sshPrompt) return;
|
||||
clearTerminalSelection();
|
||||
sshPrompt.reset();
|
||||
sshTerminal.stop();
|
||||
sshView.post(L"ssh-input:off");
|
||||
layout(owner);
|
||||
}
|
||||
|
||||
bool startSshTerminal(HWND owner,const Panel &panel)
|
||||
{
|
||||
if(panelMatchesSshPrompt() && !sshPrompt->finished) return true;
|
||||
if(sshTerminal.running())
|
||||
{
|
||||
setStatus(L"The previous SSH session is closing. Try again when it has disconnected.");
|
||||
return false;
|
||||
}
|
||||
if(!ensureTerminalView(owner,true)) return false;
|
||||
try
|
||||
{
|
||||
auto token=ks::lan::randomHex(16);
|
||||
sshTerminal.start(*panel.ftp,panel.directory,token,sshSize);
|
||||
clearTerminalSelection();
|
||||
sshPrompt=SshPrompt{active,panel.ftp->id,std::move(token),panel.directory};
|
||||
}
|
||||
catch(const std::exception &error) {setStatus(ks::wide(error.what()));return false;}
|
||||
sshView.post(L"ssh-reset");
|
||||
if(!terminalVisible) terminalRows=std::max(terminalRows,5);
|
||||
layout(owner);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool sendSshCommand(HWND owner,const fs::path &directory,const std::wstring &value)
|
||||
{
|
||||
const auto text=ks::utf8(value);
|
||||
const auto command=directory==sshPrompt->shellDirectory?text:
|
||||
"if "+sshChangeDirectory(directory)+"; then eval "+sshShellQuote(text)+"; fi";
|
||||
if(!sshTerminal.write(command+"\r"))
|
||||
{
|
||||
setStatus(L"Could not send input to the SSH terminal.");
|
||||
return false;
|
||||
}
|
||||
sshPrompt->panelDirectory=directory;
|
||||
sshPrompt->waiting=true;
|
||||
sshPrompt->raw=true;
|
||||
sshView.post(L"ssh-input:on");
|
||||
if(GetForegroundWindow()==owner)
|
||||
{
|
||||
sshView.focus();
|
||||
sshView.post(L"ssh-focus");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool submitSshCommand(HWND owner,const Panel &panel,const std::wstring &value)
|
||||
{
|
||||
if(!startSshTerminal(owner,panel)) return false;
|
||||
if(!sshPrompt->waiting) return sendSshCommand(owner,panel.directory,value);
|
||||
if(sshPrompt->shellDirectory.empty() && !sshPrompt->startupCommand)
|
||||
{
|
||||
sshPrompt->startupCommand=value;
|
||||
return true;
|
||||
}
|
||||
setStatus(L"The SSH prompt is busy.");
|
||||
return false;
|
||||
}
|
||||
|
||||
std::optional<fs::path> sshReportedDirectory(std::wstring_view encoded)
|
||||
{
|
||||
if(encoded.empty() || encoded.size()>49152) return {};
|
||||
DWORD length{};
|
||||
if(!CryptStringToBinaryW(encoded.data(),static_cast<DWORD>(encoded.size()),CRYPT_STRING_BASE64|CRYPT_STRING_STRICT,
|
||||
nullptr,&length,nullptr,nullptr) || !length) return {};
|
||||
auto bytes=std::string(length,'\0');
|
||||
if(!CryptStringToBinaryW(encoded.data(),static_cast<DWORD>(encoded.size()),CRYPT_STRING_BASE64|CRYPT_STRING_STRICT,
|
||||
reinterpret_cast<BYTE*>(bytes.data()),&length,nullptr,nullptr) || bytes.front()!='/' ||
|
||||
bytes.find_first_of("\\:\r\n")!=bytes.npos || bytes.find('\0')!=bytes.npos) return {};
|
||||
auto path=fs::path(ks::wide(bytes)).lexically_normal();
|
||||
return isFtpFolderPath(path)?std::optional(std::move(path)):std::nullopt;
|
||||
}
|
||||
|
||||
void acceptSshDirectory(HWND owner,std::wstring_view message)
|
||||
{
|
||||
if(!panelMatchesSshPrompt() || sshPrompt->finished || message.size()<33 || message[32]!=L':' ||
|
||||
message.substr(0,32)!=ks::wide(sshPrompt->token)) return;
|
||||
const auto reported=sshReportedDirectory(message.substr(33));
|
||||
if(!reported) return;
|
||||
auto &panel=panels[active];
|
||||
auto &prompt=*sshPrompt;
|
||||
const bool initial=prompt.shellDirectory.empty();
|
||||
const bool command=std::exchange(prompt.raw,false);
|
||||
prompt.shellDirectory=*reported;
|
||||
prompt.waiting=false;
|
||||
if(command)
|
||||
{
|
||||
sshView.post(L"ssh-input:off");
|
||||
if(GetForegroundWindow()==owner) restoreCommandFocus();
|
||||
}
|
||||
if(prompt.startupCommand)
|
||||
{
|
||||
const auto pending=std::exchange(prompt.startupCommand,{});
|
||||
if(!sendSshCommand(owner,prompt.panelDirectory,*pending) && !GetWindowTextLengthW(terminalInput))
|
||||
SetWindowTextW(terminalInput,pending->c_str());
|
||||
return;
|
||||
}
|
||||
if(panel.scan.valid() || panel.directory!=prompt.panelDirectory || panel.directory==*reported) return;
|
||||
if(initial || command)
|
||||
{
|
||||
prompt.panelDirectory=*reported;
|
||||
open(panel,*reported,false);
|
||||
}
|
||||
else setStatus(L"The SSH shell could not enter the panel folder.");
|
||||
}
|
||||
|
||||
void updateSshTerminal(HWND owner)
|
||||
{
|
||||
if(!sshPrompt) return;
|
||||
if(!panelMatchesSshPrompt()) {closeSshPrompt(owner);return;}
|
||||
if(!sshView.initialized()) return;
|
||||
const auto output=sshTerminal.takeOutput();
|
||||
if(!output.empty()) sshView.send(output);
|
||||
auto &prompt=*sshPrompt;
|
||||
if(!sshTerminal.running() && !prompt.finished)
|
||||
{
|
||||
auto reason=sshTerminal.takeError();
|
||||
if(reason.empty()) reason=L"SSH session disconnected.";
|
||||
sshView.send(ks::utf8(L"\r\n["+reason+L"]\r\n"));
|
||||
if(prompt.startupCommand && !GetWindowTextLengthW(terminalInput))
|
||||
SetWindowTextW(terminalInput,prompt.startupCommand->c_str());
|
||||
prompt.finished=true;
|
||||
prompt.raw=false;
|
||||
sshView.post(L"ssh-input:off");
|
||||
setStatus(reason);
|
||||
if(GetForegroundWindow()==owner) restoreCommandFocus();
|
||||
return;
|
||||
}
|
||||
const auto &panel=panels[active];
|
||||
if(prompt.finished || prompt.waiting || panel.scan.valid() || panel.directory==prompt.panelDirectory) return;
|
||||
prompt.panelDirectory=panel.directory;
|
||||
if(panel.directory!=prompt.shellDirectory && sshTerminal.write(sshChangeDirectory(panel.directory)+"\r"))
|
||||
prompt.waiting=true;
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
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_,{});
|
||||
}
|
||||
};
|
||||
@@ -127,7 +127,7 @@ public:
|
||||
return SUCCEEDED(web->PostWebMessageAsString(message.c_str()));
|
||||
}
|
||||
bool create(HWND host,std::function<void(const std::wstring&)> receive,std::function<void()> failed,
|
||||
bool markdown=false,std::function<bool(UINT)> handleKey={})
|
||||
bool markdown=false,std::function<bool(UINT)> handleKey={},bool ssh=false)
|
||||
{
|
||||
wchar_t exe[MAX_PATH]{};
|
||||
if(!GetModuleFileNameW(nullptr,exe,MAX_PATH)) return false;
|
||||
@@ -144,7 +144,7 @@ public:
|
||||
if(!length || length>=MAX_PATH) return false;
|
||||
const auto profile=std::filesystem::path(local)/L"KSwitcher"/(markdown?L"MarkdownWebView":L"TerminalWebView");
|
||||
const auto origin=markdown?L"kswitcher-markdown.invalid":L"kswitcher-terminal.invalid";
|
||||
const auto uri=std::wstring(L"https://")+origin+(markdown?L"/markdown.html":L"/index.html");
|
||||
const auto uri=std::wstring(L"https://")+origin+(markdown?L"/markdown.html":ssh?L"/index.html?ssh":L"/index.html");
|
||||
const auto assets=folder/L"terminal";
|
||||
if(markdown && !std::filesystem::exists(assets/L"markdown.html")) return false;
|
||||
waitForReady=!markdown;
|
||||
|
||||
Reference in new issue
Block a user