Compare commits

..
10 changed files with 278 additions and 90 deletions

No files matched your search

+14 -8
View File
@@ -545,18 +545,24 @@ Warning і початковий фокус на No.
## Панелі
- **F9 → Commands → Find files** або **Alt+F7** запускає фоновий пошук
файлів у поточній локальній папці та її підпапках. Поле приймає повне
ім’я або маску без урахування регістру. `*` відповідає довільній
файлів у поточній папці та її підпапках. Підтримуються локальні папки,
FTP, SFTP і KSwitcher LAN. Поле приймає повне ім’я або маску без
урахування регістру. `*` відповідає довільній
послідовності символів, `?` — одному символу. Приховані та системні
елементи можна включити прапорцем. Пошук не обходить junction та інші
посилання на каталоги. Esc під час пошуку зупиняє обхід і показує знайдене.
Результати відкриваються в тій самій панелі з відносними шляхами.
елементи можна включити прапорцем. У FTP і SFTP це також стосується
імен із крапкою на початку. Пошук не обходить junction та інші посилання
на каталоги, які джерело позначає як посилання. Esc зупиняє обхід.
При скасуванні або втраті з’єднання знайдені файли залишаються в панелі.
Заголовок віддалених результатів показує джерело і початкову папку,
а рядки показують відносний шлях до кожного файла.
Enter або подвійний клік відкриває папку й ставить курсор на файл.
Esc у результатах повертає вихідну папку, курсор і позначки.
У результатах F3/F4 відкривають файл, а F5/F6 працюють із позначеними
або поточним файлом, використовуючи папку іншої панелі як призначення.
F8 і Shift+Delete використовують звичайні підтвердження. Успішно
переміщені та видалені файли зникають зі списку. Ctrl+R повторює пошук
або поточним файлом. F5 використовує папку іншої панелі як призначення.
У FTP і SFTP F6 перейменовує один результат у його власній папці.
Меню Files і нижній рядок клавіш враховують джерело, виділення та
можливість копіювання в іншу панель. F8 і Shift+Delete використовують звичайні підтвердження.
Успішно перейменовані, переміщені та видалені файли зникають зі списку. Ctrl+R повторює пошук
з тією самою маскою й видимістю прихованих файлів.
- **Left/Right → Tree view** або Ctrl+F10 перемикає вигляд відповідної
+11 -9
View File
@@ -1242,13 +1242,11 @@ INT_PTR CALLBACK comparisonProgressDialog(HWND dialog,UINT message,WPARAM wp,LPA
return paintTextDialog(dialog,message,wp,lp,L" Compare files ");
}
void compareSelectedFiles(HWND owner)
bool selectedComparisonFiles(CompareFile (&files)[2])
{
auto &current=panels[active],&other=panels[1-active];
const auto selected=selectedPanelPaths(current);
const auto opposite=selectedPanelPaths(other);
auto state=std::make_unique<FileComparison>();
auto &comparison=*state;
const auto pick=[](const Panel &panel,const fs::path &path,CompareFile &file)
{
const auto row=std::find(panel.rows.begin(),panel.rows.end(),path);
@@ -1261,13 +1259,17 @@ void compareSelectedFiles(HWND owner)
file={path,label,panel.peer,panel.ftp};
return true;
};
bool valid=false;
if(selected.size()==2)
valid=pick(current,selected[0],comparison.files[0]) && pick(current,selected[1],comparison.files[1]);
else if(selected.size()==1 && opposite.size()==1)
valid=pick(current,selected.front(),comparison.files[active]) &&
pick(other,opposite.front(),comparison.files[1-active]);
if(!valid)
return pick(current,selected[0],files[0]) && pick(current,selected[1],files[1]);
return selected.size()==1 && opposite.size()==1 && pick(current,selected.front(),files[active]) &&
pick(other,opposite.front(),files[1-active]);
}
void compareSelectedFiles(HWND owner)
{
auto state=std::make_unique<FileComparison>();
auto &comparison=*state;
if(!selectedComparisonFiles(comparison.files))
{
showFilesNotice(owner,L"Mark two text files in the active panel or select one text file in each panel.",
L"Compare files");
+10 -4
View File
@@ -76,15 +76,21 @@ void startFileSearch(Panel &panel,Panel::FindOptions options)
if(panel.scanRequest) return;
cancelFolderSizes(panel);
panel.remoteRetry.reset();
panel.scanRequest=Panel::ScanRequest{.directory=panel.directory,.statusRevision=statusRevision,.find=std::move(options)};
panel.scanRequest=Panel::ScanRequest{.directory=panel.directory,.peer=panel.peer,.statusRevision=statusRevision,
.ftp=panel.ftp,.find=std::move(options)};
startDirectoryScan(panel);
}
void findLocalFiles(HWND owner,Panel &panel)
bool canFindFiles(const Panel &panel)
{
if(panel.peer || panel.ftp || panel.archive || panel.directory.empty())
return !panel.archive && !panel.directory.empty() && !transferProfileList(panel);
}
void findPanelFiles(HWND owner,Panel &panel)
{
if(!canFindFiles(panel))
{
setStatus(L"Find files requires a local folder.");
setStatus(L"Find files requires an open folder.");
return;
}
if(panel.scanRequest)
+61 -26
View File
@@ -29,45 +29,80 @@ std::unique_ptr<Panel::ScanResult> scanFileMatches(const Panel::ScanRequest &req
std::atomic_size_t &entriesRead,std::stop_token stop)
{
auto result=std::make_unique<Panel::ScanResult>();
FilesConnection local(nullptr);
std::vector<fs::path> pending{request.directory};
size_t visited=0;
while(!pending.empty() && !stop.stop_requested())
const bool remote=request.peer || request.ftp;
const auto walk=[&](const auto &listDirectory)
{
const auto directory=std::move(pending.back());
pending.pop_back();
try
std::vector<fs::path> pending{request.directory};
size_t visited=0;
while(!pending.empty() && !stop.stop_requested())
{
listFiles(local,directory,[&](const fs::path &path,const FileInfo &entry)
const auto directory=std::move(pending.back());
pending.pop_back();
try
{
if(stop.stop_requested()) return false;
entriesRead.store(++visited,std::memory_order_relaxed);
if(!request.find->includeHidden && (entry.attributes&(FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM)))
if(!listDirectory(directory,[&](const fs::path &path,const FileInfo &entry)
{
if(stop.stop_requested()) return false;
if(path.parent_path()!=folderPathWithoutSeparator(directory)) return true;
entriesRead.store(++visited,std::memory_order_relaxed);
const auto name=path.filename().native();
if(!request.find->includeHidden &&
((entry.attributes&(FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM)) ||
(request.ftp && name.starts_with(L'.')))) return true;
if(entry.attributes&FILE_ATTRIBUTE_DIRECTORY)
{
if(!(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT)) pending.push_back(path);
}
else if((!request.ftp || !(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT)) &&
matchesFileMask(name,request.find->mask) &&
result->metadata.emplace(path,FolderEntryMetadata{
entry.attributes,entry.size,entry.modified}).second)
result->files.push_back(path);
return true;
if(entry.attributes&FILE_ATTRIBUTE_DIRECTORY)
})) break;
}
catch(const std::system_error &error)
{
if(stop.stop_requested()) break;
const auto code=error.code().value();
if(remote && code!=ERROR_FILE_NOT_FOUND && code!=ERROR_PATH_NOT_FOUND &&
code!=ERROR_ACCESS_DENIED && code!=ERROR_DIRECTORY)
throw;
if(!remote && directory==request.directory)
{
if(!(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT)) pending.push_back(path);
}
else if(matchesFileMask(path.filename().native(),request.find->mask))
{
result->files.push_back(path);
result->metadata.emplace(path,FolderEntryMetadata{entry.attributes,entry.size,entry.modified});
result->failure=L"Cannot search folder: "+directory.native();
return;
}
result->error=ERROR_PARTIAL_COPY;
}
}
};
try
{
if(request.ftp)
{
TransferSession connection(*request.ftp,SftpAccess::normal,stop);
walk([&](const fs::path &directory,const FileVisitor &visit)
{
const auto error=connection.list(directory,visit,stop);
if(error==ERROR_CANCELLED) return false;
requireFileOperation(error==ERROR_SUCCESS || error==ERROR_NO_MORE_FILES,error);
return true;
});
}
catch(const std::system_error &)
else
{
if(directory==request.directory)
{
result->failure=L"Cannot search folder: "+directory.native();
return result;
}
result->error=ERROR_PARTIAL_COPY;
FilesConnection connection(request.peer?&*request.peer:nullptr,stop);
walk([&](const fs::path &directory,const FileVisitor &visit){return listFiles(connection,directory,visit);});
}
}
catch(const std::exception &)
{
if(remote) result->error=ERROR_CONNECTION_ABORTED;
else if(!stop.stop_requested()) result->failure=L"Cannot search folder: "+request.directory.native();
}
if(stop.stop_requested()) result->error=ERROR_CANCELLED;
result->opened=true;
result->opened=result->failure.empty();
std::sort(result->files.begin(),result->files.end());
return result;
}
+112 -22
View File
@@ -715,7 +715,8 @@ std::wstring panelCaption(const Panel &panel)
const auto display=panel.directory.lexically_relative(panel.archive->file.parent_path());
return L"Archive · "+display.native();
}
return panel.findOrigin?L"Search results":panelLocation(panel);
if(!panel.findOrigin) return panelLocation(panel);
return panel.ftp || panel.peer?L"Search results · "+panelLocation(panel):L"Search results";
}
Panel panels[2];
@@ -2137,6 +2138,37 @@ std::vector<fs::path> selectedPanelPaths(const Panel &panel)
return paths;
}
bool remoteSearchResults(const Panel &panel)
{
return panel.findOrigin && (panel.peer || panel.ftp);
}
bool remoteSearchActionAvailable(int command)
{
const auto &panel=panels[active];
if(!remoteSearchResults(panel)) return true;
if(command==110 || command==116) return true;
const auto row=currentPanelRow(panel);
if(row==LB_ERR || panel.scanRequest || command==115) return false;
if(command==112)
{
const auto entry=panel.metadata.find(panel.rows[row]);
return entry!=panel.metadata.end() && !(entry->second.attributes&FILE_ATTRIBUTE_READONLY);
}
if(command==114 && panel.ftp)
{
const auto marked=std::find(panel.marked.begin(),panel.marked.end(),true);
return marked==panel.marked.end() || std::find(std::next(marked),panel.marked.end(),true)==panel.marked.end();
}
if(command==113 || command==114)
{
const auto &destination=panels[1-active];
return !quickViewWindow && !destination.findOrigin && !destination.archive && !destination.ftp &&
(!panel.ftp || !destination.peer) && !destination.directory.empty();
}
return true;
}
void copyPanelNames(HWND owner)
{
const auto &panel=panels[active];
@@ -2628,6 +2660,8 @@ LRESULT CALLBACK terminalInputKeys(HWND input,UINT message,WPARAM wp,LPARAM lp,U
void updateSelectionSummary(const Panel &panel)
{
if(&panel==&panels[active] && remoteSearchResults(panel))
for(const auto key:commands) InvalidateRect(key,nullptr,FALSE);
const bool hadSummary=hasSelectionSummary();
size_t marked=0,unmeasured=0;
uint64_t total=0;
@@ -2715,6 +2749,8 @@ std::wstring folderMeasurementText(const Panel &panel,const fs::path &path,size_
void showFileDetails(const Panel &panel)
{
refreshQuickView(panel);
if(&panel==&panels[active])
for(const auto key:commands) InvalidateRect(key,nullptr,FALSE);
if(&panel==&panels[active] && showDirectoryScanProgress(panels[active])) return;
if(panel.remoteRetry)
{
@@ -2724,7 +2760,11 @@ void showFileDetails(const Panel &panel)
if(panel.findOrigin)
{
const auto error=panel.findOrigin->error;
setStatus(std::to_wstring(panel.rows.size())+(error==ERROR_CANCELLED?L" matches (stopped)":
const auto count=std::to_wstring(panel.rows.size());
if(error==ERROR_CONNECTION_ABORTED)
setStatus(count+(panel.rows.size()==1?L" match":L" matches")+
L" · Connection interrupted · Ctrl+R Retry · Esc Back");
else setStatus(count+(error==ERROR_CANCELLED?L" matches (stopped)":
error?L" matches (some folders could not be read)":L" matches")+
L" · Enter: Go · Esc: Back");
return;
@@ -2960,6 +3000,14 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
const bool sameDirectory=sameFolderPath(previousDirectory,directory,provider);
auto &[nextWatch,folders,files,metadata,error,opened,failure,ftpInitialDirectory,ordered,columnMetadata,archiveEntries]=scan;
const bool partial=error==ERROR_CANCELLED;
if(error==ERROR_CONNECTION_ABORTED && request.find && panel.findOrigin && sameDirectory && files.empty() &&
request.find->mask==panel.findOrigin->options.mask &&
request.find->includeHidden==panel.findOrigin->options.includeHidden)
{
panel.findOrigin->error=error;
if(&panel==&panels[active]) showFileDetails(panel);
return true;
}
if(!failure.empty())
{
if((!peer && !request.ftp) || &panel==&panels[active]) setStatus(failure);
@@ -3111,7 +3159,11 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
if(renderTree) appendTreeRows(panel,rows);
else if(finding)
{
for(const auto &file:files) add(file,file.lexically_relative(directory).native(),false);
for(const auto &file:files)
{
const auto relative=file.lexically_relative(directory);
add(file,panel.ftp?ftpPath(relative):relative.native(),false);
}
}
else
{
@@ -3207,7 +3259,8 @@ void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::opti
if(directory.empty() && !ftp) return;
panel.remoteRetry.reset();
if(!panel.view.revealedFile.empty() &&
(peer || ftp || panel.view.revealedFile.parent_path()!=directory)) panel.view.revealedFile.clear();
(panel.view.revealedFile.parent_path()!=folderPathWithoutSeparator(directory) ||
(!samePanelSource(panel,peer,ftp) && panel.view.revealedFile!=selection))) panel.view.revealedFile.clear();
if(directory!=panel.directory || !samePanelSource(panel,peer,ftp))
cancelFolderSizes(panel);
panel.scanRequest=Panel::ScanRequest{directory,std::move(selection),std::move(fallback),
@@ -3247,7 +3300,7 @@ void collectDirectoryScans()
try
{
auto result=panel.scan.get();
if(!result->failure.empty() && (request.peer || usesFtp) && !panel.scanStop.stop_requested())
if(!request.find && !result->failure.empty() && (request.peer || usesFtp) && !panel.scanStop.stop_requested())
{
retry=Panel::RemoteRetry{{request.directory,request.selection,usesFtp?request.ftp->id:std::string{},
request.peer,request.navigationPosition,usesFtp?request.ftp->protocol:TransferProtocol::ftp},
@@ -3633,7 +3686,7 @@ void collectFolderSizes(Panel &panel)
void openSelectedText(const Panel &panel, bool edit, bool external,bool hex=false);
ks::files::TextDialogs textWindowDialogs();
void findLocalFiles(HWND owner,Panel &panel);
void findPanelFiles(HWND owner,Panel &panel);
void compareSelectedFiles(HWND owner);
void createArchive(HWND owner,Panel &panel);
void addToArchive(HWND owner,Panel &panel,std::vector<fs::path> sources);
@@ -3793,7 +3846,7 @@ void selectDrive()
else if(menuIndex==2 && (row==4 || row==5)) openSelectedText(panels[active],row==5,true);
else if(menuIndex==2 && (row==6 || row==7)) runActivePeerAction(owner,row==7);
else if(menuIndex==2 && row==8) compareSelectedFiles(owner);
else if(menuIndex==2 && row==9) findLocalFiles(owner,panels[active]);
else if(menuIndex==2 && row==9) findPanelFiles(owner,panels[active]);
else if(menuIndex==2 && row==10) toggleQuickView(owner);
else if(menuIndex==2 && row==11) copyFullPanelPath(owner,panels[active]);
else if(menuIndex==2 && row==12) openSpaceAnalyzer(owner,panels[active]);
@@ -4527,7 +4580,8 @@ void enter(Panel &panel)
}
if(panel.findOrigin)
{
revealLocalFile(panel,target);
panel.view.revealedFile=target;
openOn(panel,target.parent_path(),false,panel.peer,target,{},panel.ftp);
return;
}
if(panel.sizes[row]==L"Folder" && toggleTreeRow(panel,static_cast<size_t>(row))) return;
@@ -6509,10 +6563,14 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
request.otherPeer=request.destinationPeer=destination.peer?&*destination.peer:nullptr;
request.sources=request.externalSources?std::move(external):selectedPanelPaths(source);
if(request.sources.empty()) return;
if(ftpRename && request.sources.size()!=1)
if(ftpRename)
{
setStatus(L"Select one remote file or folder to rename.");
return;
if(request.sources.size()!=1)
{
setStatus(L"Select one remote file or folder to rename.");
return;
}
request.destination=request.sources.front().parent_path();
}
const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(ftpRename?113:102),owner,copyDialog,
reinterpret_cast<LPARAM>(&request));
@@ -6586,6 +6644,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
throw std::system_error(ERROR_ALREADY_EXISTS,std::system_category());
if(progress.canceled) return;
sourceHost.ftp->rename(path,target);
if(fromSearch) removed.insert(path);
++copied;
++progress.files;
++progress.totalFiles;
@@ -7063,7 +7122,7 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent)
}
else host.remove(current,permanent,attributes,readOnly);
++done;
if(!panel.peer && !ftp) removed.insert(current);
removed.insert(current);
}
catch(const std::system_error &e)
{
@@ -7083,8 +7142,12 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent)
progressDialog.close();
for(auto &visible:panels)
{
if(treePanelActive(visible) && samePanelSource(panel,visible.peer,visible.ftp)) pruneTreeMarks(visible,removed);
if(visible.findOrigin) pruneSearchResults(visible,removed);
const bool sameSource=samePanelSource(panel,visible.peer,visible.ftp);
if(treePanelActive(visible) && sameSource) pruneTreeMarks(visible,removed);
if(visible.findOrigin)
{
if(sameSource) pruneSearchResults(visible,removed);
}
else if(!visible.directory.empty()) open(visible,visible.directory);
}
SetFocus(panel.list);
@@ -7834,14 +7897,37 @@ void openMenu(HWND window, int index)
L"Find files\tAlt+F7",quickViewWindow?L"Close Quick View\tCtrl+Q":L"Quick View\tCtrl+Q",
L"Copy full path\tCtrl+Shift+C",L"Space Analyzer",L"View as hex\tShift+F3",L"Viewer bookmarks…"};
}
const auto &panel=panels[active];
const bool remoteResults=remoteSearchResults(panel);
const auto resultRow=remoteResults?currentPanelRow(panel):LB_ERR;
commandActions.clear();
if(index==2)
if(index==1 && remoteResults)
{
if(remoteSearchActionAvailable(113)) commandActions.push_back(0);
if(remoteSearchActionAvailable(114))
{
if(panel.ftp) rows[1]=L"Rename\tF6";
commandActions.push_back(1);
}
commandActions.push_back(3);
}
else if(index==2)
{
commandActions={0,3,11,-1,1,13,14,2,4,5,8};
if(!panels[active].peer && !panels[active].ftp)
if(!terminalVisible && canFindFiles(panels[active])) commandActions.insert(commandActions.begin()+1,9);
if(!terminalVisible && !panels[active].peer && !panels[active].ftp)
commandActions.insert(commandActions.begin()+2,12);
if(remoteResults)
{
commandActions.insert(commandActions.begin()+1,9);
if(!terminalVisible) commandActions.insert(commandActions.begin()+2,12);
CompareFile comparison[2];
const auto view=remoteSearchActionAvailable(111);
const auto edit=remoteSearchActionAvailable(112);
const auto compare=view && selectedComparisonFiles(comparison);
std::erase_if(commandActions,[&](int action)
{
return action==4 || action==5 || (action==2 && !edit) || (action==8 && !compare) ||
(!view && (action==1 || action==13)) || (resultRow==LB_ERR && action==11);
});
}
if(quickViewWindow || (!panels[active].peer && !panels[active].ftp)) commandActions.push_back(10);
if(panels[active].peer) commandActions.insert(commandActions.end(),{-1,6,7});
@@ -8491,6 +8577,8 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
}
if(std::find(std::begin(commands),std::end(commands),item.hwndItem)!=std::end(commands))
{
if(item.CtlID==114 && remoteSearchResults(panels[active]) && panels[active].ftp)
text=L"F6 Rename";
const auto separator=text.find(L' ');
auto key=text.substr(0,separator);
if(key.starts_with(L'F') && key.size()>1) key.erase(0,1);
@@ -8499,7 +8587,8 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
action.left=shortcut.right;
paintText(item.hDC,shortcut,key.c_str(),RGB(184,184,184),RGB(0,0,0));
if(action.left<action.right)
paintText(item.hDC,action,text.c_str()+separator+1,colors[Selection],colors[Footer]);
paintText(item.hDC,action,remoteSearchActionAvailable(item.CtlID)?text.c_str()+separator+1:L"",
colors[Selection],colors[Footer]);
return TRUE;
}
const bool popupRow=item.hwndItem==picker || item.hwndItem==completionList;
@@ -8784,7 +8873,8 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
if (HIWORD(wp) == BN_CLICKED)
{
for(const auto &command:keyBar)
if(LOWORD(wp)==command.id) SendMessageW(panels[active].list,WM_KEYDOWN,command.key,0);
if(LOWORD(wp)==command.id && remoteSearchActionAvailable(command.id))
SendMessageW(panels[active].list,WM_KEYDOWN,command.key,0);
}
if (LOWORD(wp) >= 102 && LOWORD(wp) <= 103 && HIWORD(wp) == LBN_DBLCLK)
enter(panels[LOWORD(wp) - 102]);
@@ -8968,7 +9058,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
}
if(panel.findOrigin && !panel.scanRequest)
{
openOn(panel,panel.directory,false,{});
open(panel,panel.directory);
continue;
}
if(panel.folderSizeJob)
@@ -8992,7 +9082,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
hidePicker();
showMenu(false);
if(message.wParam==VK_F5) createArchive(window,panels[active]);
else findLocalFiles(window,panels[active]);
else findPanelFiles(window,panels[active]);
}
continue;
}
+12 -6
View File
@@ -83,6 +83,7 @@ class SshConnection
ks::lan::Network network_;
ks::lan::WinSocket socket_;
std::optional<std::stop_callback<std::function<void()>>> stopConnection_;
std::vector<Hop> hops_;
std::string fingerprint_;
@@ -156,12 +157,16 @@ class SshConnection
"SFTP key authentication failed (use RSA PEM without a passphrase, or ECDSA OpenSSH with its .pub file)");
}
void connectHop(const TransferProfile &profile,bool probeOnly)
void connectHop(const TransferProfile &profile,bool probeOnly,std::stop_token stop)
{
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.");
Hop hop;
if(hops_.empty()) connectSshSocket(socket_,profile);
if(hops_.empty())
{
connectSshSocket(socket_,profile);
if(stop.stop_possible()) stopConnection_.emplace(stop,[handle=socket_.value] {shutdown(handle,SD_BOTH);});
}
else
{
const auto host=ks::utf8(profile.host);
@@ -212,7 +217,7 @@ class SshConnection
}
public:
explicit SshConnection(const TransferProfile &destination,bool probeOnly=false)
explicit SshConnection(const TransferProfile &destination,bool probeOnly=false,std::stop_token stop={})
{
initializeSsh();
const auto profiles=sshProfiles.load();
@@ -222,8 +227,9 @@ public:
{
for(size_t i=0;i<route.size();++i)
{
requireFileOperation(!stop.stop_requested(),ERROR_CANCELLED);
const auto &profile=route[i];
try {connectHop(profile,probeOnly && i+1==route.size());}
try {connectHop(profile,probeOnly && i+1==route.size(),stop);}
catch(const std::exception &error)
{
if(route.size()==1) throw;
@@ -284,8 +290,8 @@ class SftpSession
}
public:
explicit SftpSession(const TransferProfile &profile,SftpAccess access=SftpAccess::normal):
connection_(profile),access_(access)
explicit SftpSession(const TransferProfile &profile,SftpAccess access=SftpAccess::normal,
std::stop_token stop={}):connection_(profile,false,stop),access_(access)
{
if(access==SftpAccess::normal)
{
+3 -2
View File
@@ -59,9 +59,10 @@ class TransferSession
std::optional<SftpSession> sftp_;
public:
explicit TransferSession(const TransferProfile &profile,SftpAccess access=SftpAccess::normal)
explicit TransferSession(const TransferProfile &profile,SftpAccess access=SftpAccess::normal,
std::stop_token stop={})
{
if(profile.protocol==TransferProtocol::sftp) sftp_.emplace(profile,access);
if(profile.protocol==TransferProtocol::sftp) sftp_.emplace(profile,access,stop);
else ftp_.emplace(profile);
}
+30 -11
View File
@@ -115,6 +115,7 @@ constexpr DWORD SocketTimeout=5000;
class Wire
{
SOCKET socket;
std::stop_token stop;
std::unique_ptr<InputCipher> tx,rx;
void bytes(void *buffer,size_t size,bool sending)
{
@@ -122,19 +123,36 @@ class Wire
const auto deadline=GetTickCount64()+SocketTimeout;
while(size)
{
if(GetTickCount64()>=deadline)
throw std::system_error(WSAETIMEDOUT,std::system_category());
if(stop.stop_requested()) throw std::system_error(ERROR_CANCELLED,std::system_category());
const auto now=GetTickCount64();
if(now>=deadline) throw std::system_error(WSAETIMEDOUT,std::system_category());
if(stop.stop_possible())
{
fd_set ready{};
FD_SET(socket,&ready);
const auto interval=static_cast<long>(std::min<ULONGLONG>(100,deadline-now));
timeval wait{0,interval*1000};
const auto available=select(0,sending?nullptr:&ready,sending?&ready:nullptr,nullptr,&wait);
if(available==SOCKET_ERROR) socketError();
if(!available) continue;
}
const auto n=sending?send(socket,next,static_cast<int>(size),0):
recv(socket,next,static_cast<int>(size),0);
if(n==SOCKET_ERROR) socketError();
if(n==SOCKET_ERROR)
{
if(stop.stop_possible() && WSAGetLastError()==WSAEWOULDBLOCK) continue;
socketError();
}
if(!n) throw std::system_error(WSAECONNRESET,std::system_category());
size-=n;
next+=n;
}
}
public:
explicit Wire(SOCKET socket):socket(socket)
explicit Wire(SOCKET socket,std::stop_token stop={}):socket(socket),stop(stop)
{
u_long nonblocking=1;
if(stop.stop_possible() && ioctlsocket(socket,FIONBIO,&nonblocking)==SOCKET_ERROR) socketError();
if(setsockopt(socket,SOL_SOCKET,SO_RCVTIMEO,reinterpret_cast<const char*>(&SocketTimeout),sizeof(SocketTimeout)) ||
setsockopt(socket,SOL_SOCKET,SO_SNDTIMEO,reinterpret_cast<const char*>(&SocketTimeout),sizeof(SocketTimeout)))
socketError();
@@ -897,7 +915,7 @@ struct FilesConnection::Impl
std::unique_ptr<Wire> wire;
FileOperations local{false};
Impl()=default;
explicit Impl(const FilesPeer *peer)
explicit Impl(const FilesPeer *peer,std::stop_token stop)
{
if(!peer) return;
const auto pairing=Json::parse(unprotect(readFile(dataDirectory()/L"lan-pairing.bin",256*1024)));
@@ -905,15 +923,16 @@ struct FilesConnection::Impl
throw std::system_error(ERROR_ACCESS_DENIED,std::system_category());
const auto id=pairing.at("id").get<std::string>();
const auto key=pairing.at("trusted").at(peer->id).at("key").get<std::string>();
connect(*peer,id,key);
connect(*peer,id,key,stop);
}
void connect(const FilesPeer &peer,const std::string &id,const std::string &key)
void connect(const FilesPeer &peer,const std::string &id,const std::string &key,std::stop_token stop={})
{
if(stop.stop_requested()) throw std::system_error(ERROR_CANCELLED,std::system_category());
network.emplace();
socket.value=::socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(socket.value==INVALID_SOCKET) socketError();
connectPeer(socket.value,peer);
wire=std::make_unique<Wire>(socket.value);
wire=std::make_unique<Wire>(socket.value,stop);
const auto nonce=randomHex(16);
wire->write({{"version",1},{"client",id},{"server",peer.id},{"nonce",nonce}});
const auto challenge=wire->read().at("challenge").get<std::string>();
@@ -929,11 +948,11 @@ DWORD hibernateFromPairedPC()
return requestSystemHibernate();
}
FilesConnection::FilesConnection(const FilesPeer *peer):impl(std::make_unique<Impl>(peer)){}
FilesConnection::FilesConnection(const FilesPeer &peer,const std::string &local,const std::string &key):
FilesConnection::FilesConnection(const FilesPeer *peer,std::stop_token stop):impl(std::make_unique<Impl>(peer,stop)){}
FilesConnection::FilesConnection(const FilesPeer &peer,const std::string &local,const std::string &key,std::stop_token stop):
impl(std::make_unique<Impl>())
{
impl->connect(peer,local,key);
impl->connect(peer,local,key,stop);
}
FilesConnection::~FilesConnection()=default;
Json FilesConnection::call(const Json &request,const FileProgress &progress)
+2 -2
View File
@@ -23,8 +23,8 @@ class FilesConnection
struct Impl;
std::unique_ptr<Impl> impl;
public:
explicit FilesConnection(const FilesPeer *peer = nullptr);
FilesConnection(const FilesPeer &peer,const std::string &local,const std::string &key);
explicit FilesConnection(const FilesPeer *peer = nullptr,std::stop_token stop={});
FilesConnection(const FilesPeer &peer,const std::string &local,const std::string &key,std::stop_token stop={});
~FilesConnection();
Json call(const Json &request, const FileProgress &progress = {});
};
+23
View File
@@ -5,6 +5,7 @@
#include <bit>
#include <atomic>
#include <fstream>
#include <future>
#include <iostream>
#include <thread>
@@ -49,6 +50,27 @@ std::string load(const fs::path &path)
return {std::istreambuf_iterator<char>(file),{}};
}
void verifyConnectionCancellation(const std::string &client,const std::string &key)
{
const auto serverId=randomHex(16);
// Keep the server listening while deliberately withholding its handshake response.
FilesListener stalled(serverId,[&](const std::string &id){return id==client?key:std::string{};},0);
require(stalled.port()!=0,"cancellation fixture did not start");
const FilesPeer peer{serverId,"127.0.0.1",L"Stalled peer",stalled.port()};
std::stop_source stop;
auto waiting=std::async(std::launch::async,[&]
{
try {FilesConnection connection(peer,client,key,stop.get_token());}
catch(const std::system_error &error) {return error.code().value();}
return 0;
});
std::this_thread::sleep_for(std::chrono::milliseconds(150));
stop.request_stop();
require(waiting.wait_for(std::chrono::seconds(3))==std::future_status::ready,
"cancellation did not stop the stalled LAN handshake");
require(waiting.get()==ERROR_CANCELLED,"stalled LAN handshake reported the wrong cancellation error");
}
void verifyDirection(const FilesPeer *sourcePeer,const FilesPeer *targetPeer,
const std::string &id,const std::string &key,const fs::path &root)
{
@@ -176,6 +198,7 @@ int main()
require(false,"unpaired client authenticated");
}
catch(const std::system_error &){}
verifyConnectionCancellation(client,key);
FilesConnection host(one,client,key);
{
const Json hibernate={{"action","hibernate"}};