Compare commits

..
15 changed files with 358 additions and 68 deletions

No files matched your search

+12
View File
@@ -91,6 +91,18 @@ Warning і початковий фокус на No.
Ctrl+C. При переході до іншої панелі чи джерела сесія від'єднується.
Для синхронізації потрібні POSIX-оболонка й утиліта `base64` на сервері.
Оболонка та SFTP мають бачити однакові абсолютні шляхи.
- **SFTP server for sudo** у профілі приймає абсолютний шлях до
серверного OpenSSH `sftp-server`. Після відмови в доступі Viewer і
Hex Viewer пропонують один повтор через `sudo` в режимі тільки читання.
F2 в Editor після відмови в доступі до запису показує окремий запит.
Відмова або Esc під час привілейованого запису залишає чернетку в Editor,
якщо заміна файла ще не завершилась. Успішна заміна зберігає POSIX-власника,
групу та біти режиму доступу.
- Серверний адміністратор має окремо дозволити потрібний варіант команди
`sudo -n` для цього облікового запису. Перегляд використовує
`sftp-server -R`, а збереження використовує `sftp-server` без цього
прапорця. Files закриває привілейоване з'єднання після операції, розриву
або тайм-ауту мережевого запиту. Пароль sudo не запитується.
- Для SFTP використовуються ключі хоста ECDSA або RSA з підписом SHA‑2.
F3 і F4 відкривають Viewer та Editor. F2 в Editor перевіряє розмір і час
зміни віддаленого файла перед збереженням. F5 копіює між локальною
+22
View File
@@ -0,0 +1,22 @@
# Apply the exec-channel variant of SFTP initialization to the pinned library.
file(REAL_PATH ".." source_parent)
set(patch_file "${CMAKE_CURRENT_BINARY_DIR}/.kswitcher-sftp-command.patch")
configure_file("${PATCH}" "${patch_file}" @ONLY NEWLINE_STYLE LF)
set(patch_git "${CMAKE_COMMAND}" -E env "GIT_CEILING_DIRECTORIES=${source_parent}" "${GIT}")
execute_process(COMMAND ${patch_git} apply --unidiff-zero --check "${patch_file}"
RESULT_VARIABLE can_apply ERROR_QUIET)
if(can_apply EQUAL 0)
execute_process(COMMAND ${patch_git} apply --unidiff-zero "${patch_file}" COMMAND_ERROR_IS_FATAL ANY)
else()
execute_process(COMMAND ${patch_git} apply --unidiff-zero --reverse --check "${patch_file}"
RESULT_VARIABLE already_applied)
if(NOT already_applied EQUAL 0)
message(FATAL_ERROR "Could not apply the SFTP command patch")
endif()
endif()
file(REMOVE "${patch_file}")
file(STRINGS "include/libssh2_sftp.h" exec_api REGEX "^libssh2_sftp_init_command")
if(NOT exec_api)
message(FATAL_ERROR "The SFTP command API is missing after applying the patch")
endif()
+7 -1
View File
@@ -1,10 +1,16 @@
include(FetchContent)
find_package(Git REQUIRED)
set(kswitcher_ssh_patch "${CMAKE_CURRENT_LIST_DIR}/libssh2-sftp-command.patch")
file(SHA256 "${kswitcher_ssh_patch}" kswitcher_ssh_patch_hash)
# This revision includes the published SFTP security fixes after the 1.11.1 release.
FetchContent_Declare(kswitcher_libssh2
URL https://codeload.github.com/libssh2/libssh2/tar.gz/dd1546700d0ed8ff7138bc1ccc288286fb3ab2b4
URL_HASH SHA256=67d20d434055faef76439c6829ab253c892fcdd68d9a9c86cf5824bd8366e6eb
DOWNLOAD_EXTRACT_TIMESTAMP TRUE)
DOWNLOAD_EXTRACT_TIMESTAMP TRUE
PATCH_COMMAND "${CMAKE_COMMAND}" "-DGIT=${GIT_EXECUTABLE}"
"-DPATCH=${kswitcher_ssh_patch}" "-DPATCH_HASH=${kswitcher_ssh_patch_hash}"
-P "${CMAKE_CURRENT_LIST_DIR}/ApplyFilesSshPatch.cmake")
function(kswitcher_add_ssh_library)
set(BUILD_STATIC_LIBS ON)
+35
View File
@@ -0,0 +1,35 @@
diff --git a/include/libssh2_sftp.h b/include/libssh2_sftp.h
--- a/include/libssh2_sftp.h
+++ b/include/libssh2_sftp.h
@@ -226,0 +227,2 @@
+LIBSSH2_API LIBSSH2_SFTP *
+libssh2_sftp_init_command(LIBSSH2_SESSION *session, const char *command);
diff --git a/src/sftp.c b/src/sftp.c
--- a/src/sftp.c
+++ b/src/sftp.c
@@ -758 +758,2 @@
-static LIBSSH2_SFTP *sftp_init(LIBSSH2_SESSION *session)
+static LIBSSH2_SFTP *sftp_init(LIBSSH2_SESSION *session,
+ const char *command)
@@ -811,3 +812,5 @@
- "subsystem",
- sizeof("subsystem") - 1,
- "sftp", sizeof("sftp") - 1);
+ command ? "exec" : "subsystem",
+ command ? 4 : 9,
+ command ? command : "sftp",
+ command ?
+ strlen(command) : 4);
@@ -1011 +1014,2 @@
-LIBSSH2_SFTP *libssh2_sftp_init(LIBSSH2_SESSION *session)
+LIBSSH2_SFTP *libssh2_sftp_init_command(LIBSSH2_SESSION *session,
+ const char *command)
@@ -1024 +1028 @@
- BLOCK_ADJUST_ERRNO(ptr, session, sftp_init(session));
+ BLOCK_ADJUST_ERRNO(ptr, session, sftp_init(session, command));
@@ -1025,0 +1030,5 @@
+}
+
+LIBSSH2_SFTP *libssh2_sftp_init(LIBSSH2_SESSION *session)
+{
+ return libssh2_sftp_init_command(session, NULL);
+4 -2
View File
@@ -575,8 +575,10 @@ BEGIN
FAR_EDIT(388, 0, 16, 96, 182, 15)
LTEXT "&Password or key passphrase", 389, 210, 83, 194, 12
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 "Private &key file (optional)", 562, 16, 117, 182, 12
FAR_EDIT(563, 0, 16, 130, 182, 15)
LTEXT "SFTP ser&ver for sudo (optional)", 569, 210, 117, 194, 12
FAR_EDIT(570, 0, 210, 130, 194, 15)
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
+11
View File
@@ -17,6 +17,7 @@ struct TransferProfile
fs::path privateKey;
std::string hostFingerprint;
std::string jumpProfile;
std::wstring sudoSftpServer;
};
struct TransferProfiles
@@ -55,6 +56,13 @@ std::vector<TransferProfile> sshRoute(const TransferProfile &destination,
return route;
}
bool validSudoSftpServer(std::wstring_view path)
{
constexpr std::wstring_view pathCharacters=L"/-._0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
return path.empty() || (path.starts_with(L'/') && path.ends_with(L"/sftp-server") &&
path.size()<=255 && path.find_first_not_of(pathCharacters)==path.npos);
}
constexpr DWORD transferProfilesMaxBytes=1024*1024;
const fs::path ftpRoot=L"\\";
@@ -83,6 +91,7 @@ bool saveTransferProfiles(TransferProtocol protocol,const std::vector<TransferPr
row["privateKey"]=ks::utf8(profile.privateKey.native());
row["hostFingerprint"]=profile.hostFingerprint;
row["jumpProfile"]=profile.jumpProfile;
row["sudoSftpServer"]=ks::utf8(profile.sudoSftpServer);
}
rows.push_back(std::move(row));
}
@@ -131,6 +140,8 @@ 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{});
profile.sudoSftpServer=ks::wide(row.value("sudoSftpServer",std::string{}));
if(!validSudoSftpServer(profile.sudoSftpServer)) return false;
}
profiles.push_back(std::move(profile));
}
+3
View File
@@ -174,8 +174,11 @@ FileInfo uploadTransferFile(FilesConnection &local,TransferSession &ftp,const fs
if(expected && (!existing || existing->size!=expected->size || existing->modified!=expected->modified))
throw std::runtime_error("The "+ks::utf8(ftp.label())+" file changed since it was opened. Your edits are still in the editor.");
if(existing)
{
requireFileOperation(replace && !(existing->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)),
ERROR_ALREADY_EXISTS);
ftp.prepareReplacement(temporary,target);
}
requireFileOperation(!progress || progress(done,info.size),ERROR_CANCELLED);
ftp.rename(temporary,target,existing.has_value());
return *uploaded;
+8 -2
View File
@@ -2,6 +2,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,jumpVia=567,jumpLabel=568;
constexpr int sudoLabel=569,sudoServer=570;
struct Edit
{
@@ -91,6 +92,9 @@ 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;
profile.sudoSftpServer=trimFilesField(shortcutField(dialog,sudoServer));
if(!validSudoSftpServer(profile.sudoSftpServer))
return invalid(sudoServer,L"Enter the absolute path to sftp-server, for example /usr/lib/openssh/sftp-server.");
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];
@@ -123,7 +127,7 @@ std::optional<TransferProfile> readProfile(HWND dialog,const Edit &edit)
template<class Task>
bool runTest(HWND dialog,Edit &edit,const wchar_t *status,Task task)
{
constexpr int controls[]{name,host,port,user,password,keyFile,jumpVia,testConnection,forgetKey,IDOK};
constexpr int controls[]{name,host,port,user,password,keyFile,jumpVia,sudoServer,testConnection,forgetKey,IDOK};
edit.testing=true;
edit.canceled=false;
for(const auto id:controls) EnableWindow(GetDlgItem(dialog,id),FALSE);
@@ -188,7 +192,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,jumpVia,jumpLabel})
for(const auto id:{381,383,384,387,389,legacy,IDOK,IDCANCEL,keyLabel,hostStatus,jumpVia,jumpLabel,sudoLabel})
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);
@@ -201,6 +205,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());
SendDlgItemMessageW(dialog,sudoServer,EM_SETLIMITTEXT,255,0);
SetDlgItemTextW(dialog,sudoServer,profile.sudoSftpServer.c_str());
populateJumpChoices(dialog,*edit);
installFarCombo(GetDlgItem(dialog,jumpVia),GetDlgItem(dialog,keyFile));
showHostStatus(dialog,*edit);
+22 -7
View File
@@ -34,6 +34,8 @@ struct ImageView
std::vector<fs::path> images;
size_t position{};
ImageLoad load;
ImageLoadRetry retry;
bool retried{};
std::function<void(HWND)> onClose;
std::array<HWND,6> buttons{};
HFONT font{};
@@ -116,6 +118,7 @@ struct ImageView
requested=path;
++revision;
stop.request_stop();
retried=false;
error.clear();
if(bitmap) DeleteObject(std::exchange(bitmap,nullptr));
width=height=0;
@@ -154,21 +157,32 @@ struct ImageView
if(reading.valid())
{
if(reading.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return;
const auto current=revision==started;
if(current) KillTimer(window,imageTimer);
bool retryApproved=false;
try
{
auto image=reading.get();
if(revision==started) show(std::move(image));
if(current) show(std::move(image));
}
catch(const std::exception &e)
catch(const std::exception &failure)
{
if(revision==started) error=wide(e.what());
if(current)
{
if(!retried && retry.approve) retryApproved=retry.approve(window,requested,failure);
if(!retryApproved) error=wide(failure.what());
}
}
if(revision==started)
if(current && !retryApproved)
{
KillTimer(window,imageTimer);
InvalidateRect(window,nullptr,FALSE);
return;
}
if(retryApproved)
{
retried=true;
SetTimer(window,imageTimer,30,nullptr);
}
}
if(requested.empty())
{
@@ -177,7 +191,7 @@ struct ImageView
}
stop=std::stop_source{};
started=revision;
std::packaged_task<ImageRaster()> task([path=requested,decoder=load,token=stop.get_token()]
std::packaged_task<ImageRaster()> task([path=requested,decoder=retried?retry.load:load,token=stop.get_token()]
{
return decoder?decoder(path,token):decodeImage(path,path,token);
});
@@ -421,7 +435,7 @@ LRESULT CALLBACK imageProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp)
}
HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector<std::filesystem::path> images,
const std::filesystem::path &initial,ImageLoad load,std::function<void(HWND)> onClose)
const std::filesystem::path &initial,ImageLoad load,std::function<void(HWND)> onClose,ImageLoadRetry retry)
{
const auto instance=GetModuleHandleW(nullptr);
static const bool registered=[instance]
@@ -439,6 +453,7 @@ HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector<s
state->style=style;
state->images=std::move(images);
state->load=std::move(load);
state->retry=std::move(retry);
state->onClose=std::move(onClose);
const auto position=std::find(state->images.begin(),state->images.end(),initial);
if(position!=state->images.end()) state->position=static_cast<size_t>(position-state->images.begin());
+8 -1
View File
@@ -3,11 +3,18 @@
#include "files_image_decode.h"
#include <windows.h>
#include <functional>
#include <exception>
namespace ks::files
{
using ImageLoad=std::function<ImageRaster(const std::filesystem::path &,std::stop_token)>;
struct ImageLoadRetry
{
ImageLoad load;
std::function<bool(HWND,const std::filesystem::path &,const std::exception &)> approve;
};
struct ImageViewStyle
{
LOGFONTW font{};
@@ -16,6 +23,6 @@ struct ImageViewStyle
};
HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector<std::filesystem::path> images,
const std::filesystem::path &initial,ImageLoad load={},std::function<void(HWND)> onClose={});
const std::filesystem::path &initial,ImageLoad load={},std::function<void(HWND)> onClose={},ImageLoadRetry retry={});
void showImageViewFile(HWND window,const std::filesystem::path &path);
}
+39 -13
View File
@@ -6140,33 +6140,59 @@ ks::files::RemoteTextSource transferTextSource(const TransferProfile &profile)
{
auto identity=Json::array({ks::utf8(transferProtocolName(profile.protocol)),ks::utf8(ks::lower(profile.host)),
profile.port,ks::utf8(profile.user)}).dump();
return {std::move(identity),profile.name,
[profile](const fs::path &path,const fs::path &cache,bool edit,
const auto reader=[profile](SftpAccess access) -> ks::files::RemoteTextSource::Download
{
return [profile,access](const fs::path &path,const fs::path &cache,bool edit,
const ks::files::RemoteTextSource::Progress &progress,uint64_t limit)
{
requireFileOperation(!progress || progress(0,0),ERROR_CANCELLED);
TransferSession ftp(profile);
TransferSession ftp(profile,access);
const auto info=transferEntry(transferChildren(ftp,path.parent_path()),path);
requireFileOperation(info.has_value(),ERROR_FILE_NOT_FOUND);
requireFileOperation(!(info->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)),
ERROR_NOT_SUPPORTED);
const bool editable=!(info->attributes&FILE_ATTRIBUTE_READONLY);
const bool editable=access!=SftpAccess::sudoRead && !(info->attributes&FILE_ATTRIBUTE_READONLY);
if(edit && !editable) throw std::runtime_error("The "+ks::utf8(transferProtocolName(profile.protocol))+" file is read-only.");
if(info->size>limit) throw std::system_error(ERROR_FILE_TOO_LARGE,std::system_category());
FilesConnection local;
downloadTransferFile(ftp,local,path,cache,*info,false,progress);
return ks::files::RemoteTextRevision{info->size,info->modified,editable};
},
[profile](const fs::path &path,const fs::path &cache,const ks::files::RemoteTextRevision &expected)
};
};
const auto write=[profile](SftpAccess access,const fs::path &path,const fs::path &cache,
const ks::files::RemoteTextRevision &expected,const ks::files::RemoteTextSource::Progress &progress)
{
requireFileOperation(!progress || progress(0,0),ERROR_CANCELLED);
FilesConnection local;
const auto info=statFile(local,cache);
requireFileOperation(info.has_value(),ERROR_FILE_NOT_FOUND);
TransferSession ftp(profile,access);
requireFileOperation(!progress || progress(0,0),ERROR_CANCELLED);
const auto result=uploadTransferFile(local,ftp,cache,path,*info,true,progress,&expected);
return ks::files::RemoteTextRevision{result.size,result.modified,expected.editable};
};
ks::files::RemoteTextSource source{std::move(identity),profile.name,reader(SftpAccess::normal),
[write](const auto &path,const auto &cache,const auto &expected)
{
FilesConnection local;
const auto info=statFile(local,cache);
requireFileOperation(info.has_value(),ERROR_FILE_NOT_FOUND);
TransferSession ftp(profile);
const auto result=uploadTransferFile(local,ftp,cache,path,*info,true,
[](uint64_t,uint64_t){return true;},&expected);
return ks::files::RemoteTextRevision{result.size,result.modified,expected.editable};
return write(SftpAccess::normal,path,cache,expected,{});
}};
if(profile.protocol==TransferProtocol::sftp && !profile.sudoSftpServer.empty())
{
source.elevation=ks::files::RemoteTextSource::Elevation{reader(SftpAccess::sudoRead),
[write](const auto &path,const auto &cache,const auto &expected,const auto &progress)
{
return write(SftpAccess::sudoWrite,path,cache,expected,progress);
},[name=profile.name](HWND owner,const fs::path &path,bool write)
{
const auto action=write?L"Retry this save with temporary sudo write access?":
L"Open this file with temporary read-only sudo access?";
const auto message=std::wstring(L"The SFTP server denied access.\r\n\r\n")+action+
L"\r\n\r\n"+name+L" · "+ftpPath(path);
return showFilesNotice(owner,message.c_str(),write?L"SFTP save with sudo":L"SFTP read with sudo",
{.confirm=true})==IDYES;
}};
}
return source;
}
bool countCopy(CopyHost &host,const fs::path &path,CopyProgress &progress)
+53 -5
View File
@@ -267,18 +267,37 @@ fs::path sftpInitialDirectory(LIBSSH2_SFTP *sftp)
return value;
}
enum class SftpAccess { normal, sudoRead, sudoWrite };
class SftpSession
{
SshConnection connection_;
const SftpAccess access_;
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)
void requireWriteAccess() const
{
sftp_.reset(libssh2_sftp_init(connection_.session()));
if(!sftp_) connection_.operationError("Could not start the SFTP subsystem");
if(access_==SftpAccess::sudoRead)
throw std::system_error(ERROR_ACCESS_DENIED,std::system_category(),"The sudo SFTP session is read-only");
}
public:
explicit SftpSession(const TransferProfile &profile,SftpAccess access=SftpAccess::normal):
connection_(profile),access_(access)
{
if(access==SftpAccess::normal)
{
sftp_.reset(libssh2_sftp_init(connection_.session()));
if(!sftp_) connection_.operationError("Could not start the SFTP subsystem");
return;
}
if(profile.sudoSftpServer.empty() || !validSudoSftpServer(profile.sudoSftpServer))
throw std::runtime_error("Configure the absolute sftp-server path for sudo in this SFTP profile.");
const auto command="sudo -n -- "+ks::utf8(profile.sudoSftpServer)+(access==SftpAccess::sudoRead?" -R":"");
sftp_.reset(libssh2_sftp_init_command(connection_.session(),command.c_str()));
if(!sftp_) connection_.operationError("Could not start sudo SFTP. Verify the sftp-server path and the server's sudo authorization");
}
[[noreturn]] void operationError(const char *operation) const
@@ -287,7 +306,7 @@ public:
{
const auto status=libssh2_sftp_last_error(sftp_.get());
if(status==LIBSSH2_FX_PERMISSION_DENIED)
throw std::system_error(ERROR_ACCESS_DENIED,std::system_category(),operation);
throw ks::files::RemoteAccessDenied(operation);
if(status==LIBSSH2_FX_NO_SUCH_FILE || status==LIBSSH2_FX_NO_SUCH_PATH)
throw std::system_error(ERROR_FILE_NOT_FOUND,std::system_category(),operation);
if(status==LIBSSH2_FX_FILE_ALREADY_EXISTS)
@@ -338,6 +357,7 @@ public:
SftpFile open(const fs::path &path,bool write) const
{
if(write) requireWriteAccess();
const auto name=encode(path);
const auto flags=write?LIBSSH2_FXF_WRITE|LIBSSH2_FXF_CREAT|LIBSSH2_FXF_EXCL:LIBSSH2_FXF_READ;
SftpFile file(libssh2_sftp_open_ex(sftp_.get(),name.c_str(),static_cast<unsigned>(name.size()),
@@ -348,19 +368,47 @@ public:
void makeDirectory(const fs::path &path) const
{
requireWriteAccess();
const auto name=encode(path);
if(libssh2_sftp_mkdir(sftp_.get(),name.c_str(),0755)) operationError("Could not create the SFTP folder");
}
void remove(const fs::path &path,bool directory) const
{
requireWriteAccess();
const auto name=encode(path);
const auto result=directory?libssh2_sftp_rmdir(sftp_.get(),name.c_str()):libssh2_sftp_unlink(sftp_.get(),name.c_str());
if(result) operationError("Could not remove the SFTP entry");
}
void prepareReplacement(const fs::path &staged,const fs::path &existing) const
{
if(access_!=SftpAccess::sudoWrite) return;
const auto source=encode(existing),target=encode(staged);
LIBSSH2_SFTP_ATTRIBUTES attributes{};
if(libssh2_sftp_lstat(sftp_.get(),source.c_str(),&attributes))
operationError("Could not read the file ownership and permissions");
constexpr auto metadata=LIBSSH2_SFTP_ATTR_UIDGID|LIBSSH2_SFTP_ATTR_PERMISSIONS;
if((attributes.flags&metadata)!=metadata || !LIBSSH2_SFTP_S_ISREG(attributes.permissions))
throw std::runtime_error("The server did not supply the file ownership and permissions. The original was kept.");
const auto original=attributes;
attributes.flags=LIBSSH2_SFTP_ATTR_UIDGID;
if(libssh2_sftp_setstat(sftp_.get(),target.c_str(),&attributes))
operationError("Could not preserve the file ownership");
attributes.flags=LIBSSH2_SFTP_ATTR_PERMISSIONS;
attributes.permissions=original.permissions&07777;
if(libssh2_sftp_setstat(sftp_.get(),target.c_str(),&attributes))
operationError("Could not preserve the file permissions");
if(libssh2_sftp_lstat(sftp_.get(),target.c_str(),&attributes))
operationError("Could not verify the staged file permissions");
if((attributes.flags&metadata)!=metadata || attributes.uid!=original.uid ||
attributes.gid!=original.gid || (attributes.permissions&07777)!=(original.permissions&07777))
throw std::runtime_error("The server did not preserve ownership and permissions. The original was kept.");
}
void rename(const fs::path &from,const fs::path &to,bool replace) const
{
requireWriteAccess();
const auto source=encode(from),target=encode(to);
if(replace)
{
+103 -31
View File
@@ -647,22 +647,26 @@ struct RemoteTextFile
std::filesystem::remove(cache.parent_path(),ignored);
}
void download(bool edit,const RemoteTextSource::Progress &progress,uint64_t sizeLimit=UINT64_MAX)
void download(bool edit,const RemoteTextSource::Progress &progress,uint64_t sizeLimit=UINT64_MAX,bool elevated=false)
{
GUID id{};
wchar_t name[40]{};
if(FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id,name,40))
throw std::runtime_error("Cannot create a temporary directory for the remote file.");
const auto directory=std::filesystem::temp_directory_path()/(L"ks-files-edit-"+std::wstring(name));
if(!std::filesystem::create_directory(directory))
throw std::runtime_error("Cannot create a temporary directory for the remote file.");
cache=directory/L"content";
revision=source.download(original,cache,edit,progress,sizeLimit);
if(cache.empty())
{
GUID id{};
wchar_t name[40]{};
if(FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id,name,40))
throw std::runtime_error("Cannot create a temporary directory for the remote file.");
const auto directory=std::filesystem::temp_directory_path()/(L"ks-files-edit-"+std::wstring(name));
if(!std::filesystem::create_directory(directory))
throw std::runtime_error("Cannot create a temporary directory for the remote file.");
cache=directory/L"content";
}
const auto &read=elevated?source.elevation->download:source.download;
revision=read(original,cache,edit,progress,sizeLimit);
}
void upload()
void upload(const RemoteTextSource::Progress &cancel)
{
revision=source.upload(original,cache,revision);
revision=cancel?source.elevation->upload(original,cache,revision,cancel):source.upload(original,cache,revision);
}
};
@@ -902,9 +906,10 @@ private:
std::future<std::string> image;
ImageRequest activeImage;
std::shared_ptr<std::atomic<bool>> cancelImages;
std::atomic<bool> cancelOpen{};
std::atomic<bool> cancelOpen{},cancelElevatedSave{};
std::future<void> opening;
std::future<bool> saving;
bool elevatedOpen{},elevatedSave{};
static constexpr UINT_PTR saveTimer = 1;
static constexpr UINT_PTR openTimer = 2;
static constexpr UINT_PTR previewTimer = 3;
@@ -964,6 +969,7 @@ private:
void invalidateHints() const;
void initializeDocument(std::optional<std::string> firstPage={});
void startRemoteOpen(bool elevated=false);
void finishOpen();
void createMenu();
void releaseMenu();
@@ -986,7 +992,7 @@ private:
void pickBookmark(bool currentFile);
void stagePage();
void go(uint64_t index);
void saveFile(bool closeWhenDone);
void saveFile(bool closeWhenDone,bool elevated=false);
void finishSave();
void requestClose();
void toggleMode();
@@ -1677,6 +1683,24 @@ void TextWindow::pollQuickView()
std::thread(std::move(task)).detach();
}
void TextWindow::startRemoteOpen(bool elevated)
{
elevatedOpen=elevated;
if(!SetTimer(window,openTimer,75,nullptr)) throw std::runtime_error("Cannot start the remote file timer.");
try
{
opening=std::async(std::launch::async,[this,elevated]
{
remote->download(edit,[this](uint64_t,uint64_t){return !cancelOpen;},UINT64_MAX,elevated);
});
}
catch(...)
{
KillTimer(window,openTimer);
throw;
}
}
void TextWindow::finishOpen()
{
if(!opening.valid() || opening.wait_for(std::chrono::milliseconds(0))!=std::future_status::ready) return;
@@ -1689,6 +1713,18 @@ void TextWindow::finishOpen()
initializeDocument();
invalidate();
}
catch(const RemoteAccessDenied &error)
{
if(!cancelOpen && !edit && !elevatedOpen && remote->source.elevation)
{
if(remote->source.elevation->approve(window,original,false))
startRemoteOpen(true);
else DestroyWindow(window);
return;
}
if(!cancelOpen) search.style.message(window,wide(error.what()).c_str());
DestroyWindow(window);
}
catch(const std::exception &error)
{
if(!cancelOpen) search.style.message(window,wide(error.what()).c_str());
@@ -1696,7 +1732,7 @@ void TextWindow::finishOpen()
}
}
void TextWindow::saveFile(bool closeWhenDone)
void TextWindow::saveFile(bool closeWhenDone,bool elevated)
{
if (busy() || savedViewerLoad.valid() || !edit) return;
auto destination=original;
@@ -1710,17 +1746,22 @@ void TextWindow::saveFile(bool closeWhenDone)
pendingCaret = send(SCI_GETCURRENTPOS);
if(draft) pendingSavePath=destination;
closeAfterSave = closeWhenDone;
elevatedSave=elevated;
cancelElevatedSave=false;
if (!SetTimer(window, saveTimer, 75, nullptr)) throw std::runtime_error("Cannot start the save timer.");
send(SCI_SETREADONLY, TRUE);
try
{
saving=std::async(std::launch::async,[this,destination=std::move(destination)]
saving=std::async(std::launch::async,[this,destination=std::move(destination),elevated]
{
const auto reopened=draft?document->saveNew(destination,newFormat):document->save();
if(remote)
{
uploadPending=true;
remote->upload();
const auto progress=elevated?RemoteTextSource::Progress([this](uint64_t,uint64_t) {
return !cancelElevatedSave;
}):RemoteTextSource::Progress{};
remote->upload(progress);
uploadPending=false;
}
return reopened;
@@ -1745,7 +1786,22 @@ void TextWindow::finishSave()
return;
}
send(SCI_SETREADONLY, !edit);
const auto reopened = saving.get();
bool reopened{};
try {reopened=saving.get();}
catch(const RemoteAccessDenied &)
{
if(!remote || elevatedSave || !remote->source.elevation) throw;
if(remote->source.elevation->approve(window,original,true)) saveFile(closeAfterSave,true);
else {closeAfterSave=false;invalidate();}
return;
}
catch(const std::system_error &error)
{
if(!elevatedSave || error.code().value()!=ERROR_CANCELLED) throw;
closeAfterSave=false;
invalidate();
return;
}
stagedDirty = false;
const bool created=std::exchange(draft,false);
if(created)
@@ -1781,7 +1837,11 @@ void TextWindow::finishSave()
void TextWindow::requestClose()
{
if (opening.valid()) { cancelOpen=true; return; }
if (busy()) return;
if (busy())
{
if(elevatedSave) cancelElevatedSave=true;
return;
}
cancelSavedViewerLoad();
if (needsSave())
{
@@ -2651,7 +2711,7 @@ void TextWindow::find(bool down, DWORD flags)
void TextWindow::command(UINT id)
{
if(!document && id!=close) return;
if (busy()) return;
if (busy() && id!=close) return;
if(hex && (id==switchMode || id==historyBack || id==historyForward || id==findText || id==findNext ||
id==findPrevious || id==lexerAuto || id==lexerPlain || id>=lexerStart)) return;
switch (id)
@@ -2877,12 +2937,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
{
self->applyPreferences();
self->send(SCI_SETREADONLY,TRUE);
if(!SetTimer(window,openTimer,75,nullptr))
throw std::runtime_error("Cannot start the remote file timer.");
self->opening=std::async(std::launch::async,[state=self.get()]
{
state->remote->download(state->edit,[state](uint64_t,uint64_t){return !state->cancelOpen;});
});
self->startRemoteOpen();
}
else if(self->embedded) self->applyPreferences();
else self->initializeDocument();
@@ -3228,18 +3283,35 @@ void openImageWindow(HWND owner,std::vector<std::filesystem::path> images,const
{
const auto backend=source?std::optional(*source):peer?std::optional(lanTextSource(*peer)):std::nullopt;
ImageLoad load;
ImageLoadRetry retry;
if(backend)
load=[backend=*backend](const std::filesystem::path &original,std::stop_token stop) {
RemoteTextFile file(backend,original);
file.download(false,[&](uint64_t,uint64_t){return !stop.stop_requested();},imageSourceLimit);
return decodeImage(file.cache,original,stop);
{
const auto reader=[&](bool elevated) -> ImageLoad
{
return [backend=*backend,elevated](const std::filesystem::path &original,std::stop_token stop)
{
RemoteTextFile file(backend,original);
file.download(false,[&](uint64_t,uint64_t){return !stop.stop_requested();},imageSourceLimit,elevated);
return decodeImage(file.cache,original,stop);
};
};
load=reader(false);
if(backend->elevation)
{
retry.load=reader(true);
retry.approve=[approve=backend->elevation->approve](HWND window,
const std::filesystem::path &file,const std::exception &failure)
{
return dynamic_cast<const RemoteAccessDenied*>(&failure) && approve(window,file,false);
};
}
}
if(!textWindows.contains(owner)) filesOwner=owner;
const auto window=createImageView(owner,false,imageViewStyle(dialogs),std::move(images),path,std::move(load),
[](HWND closed) {
std::erase(textWindowOrder,closed);
quitWhenFilesWindowsClose();
});
},std::move(retry));
if(!window) throw std::runtime_error("Could not open the image viewer.");
textWindowOrder.push_back(window);
const auto instance=GetModuleHandleW(nullptr);
+24 -4
View File
@@ -3,6 +3,8 @@
#include <windows.h>
#include <filesystem>
#include <functional>
#include <optional>
#include <system_error>
#include <cstdint>
#include <string_view>
#include <vector>
@@ -71,15 +73,33 @@ struct RemoteTextRevision
bool editable{};
};
struct RemoteAccessDenied : std::system_error
{
explicit RemoteAccessDenied(const char *operation):
std::system_error(ERROR_ACCESS_DENIED,std::system_category(),operation) {}
};
struct RemoteTextSource
{
using Progress=std::function<bool(uint64_t,uint64_t)>;
using Download=std::function<RemoteTextRevision(const std::filesystem::path &,const std::filesystem::path &,
bool,const Progress &,uint64_t)>;
using Upload=std::function<RemoteTextRevision(const std::filesystem::path &,const std::filesystem::path &,
const RemoteTextRevision &)>;
struct Elevation
{
Download download;
std::function<RemoteTextRevision(const std::filesystem::path &,const std::filesystem::path &,
const RemoteTextRevision &,const Progress &)> upload;
std::function<bool(HWND,const std::filesystem::path &,bool)> approve;
};
std::string id;
std::wstring name;
std::function<RemoteTextRevision(const std::filesystem::path &,const std::filesystem::path &,
bool,const Progress &,uint64_t)> download;
std::function<RemoteTextRevision(const std::filesystem::path &,const std::filesystem::path &,
const RemoteTextRevision &)> upload;
Download download;
Upload upload;
std::optional<Elevation> elevation;
};
RemoteTextSource createLanTextSource(const lan::FilesPeer &peer);
+7 -2
View File
@@ -59,9 +59,9 @@ class TransferSession
std::optional<SftpSession> sftp_;
public:
explicit TransferSession(const TransferProfile &profile)
explicit TransferSession(const TransferProfile &profile,SftpAccess access=SftpAccess::normal)
{
if(profile.protocol==TransferProtocol::sftp) sftp_.emplace(profile);
if(profile.protocol==TransferProtocol::sftp) sftp_.emplace(profile,access);
else ftp_.emplace(profile);
}
@@ -101,6 +101,11 @@ public:
FtpDeleteFileA(ftp_->handle(),name.c_str()));
}
void prepareReplacement(const fs::path &staged,const fs::path &existing)
{
if(sftp_) sftp_->prepareReplacement(staged,existing);
}
void rename(const fs::path &from,const fs::path &to,bool replace=false)
{
if(sftp_) {sftp_->rename(from,to,replace);return;}