| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150 |
- //---------------------------------------------------------------------------
- #include <vcl.h>
- #pragma hdrstop
- #include "Terminal.h"
- #include <SysUtils.hpp>
- #include <FileCtrl.hpp>
- #include "Common.h"
- #include "FileBuffer.h"
- #include "FileSystems.h"
- #include "Interface.h"
- #include "RemoteFiles.h"
- #include "ScpFileSystem.h"
- #include "SftpFileSystem.h"
- #include "TextsCore.h"
- //---------------------------------------------------------------------------
- #pragma package(smart_init)
- //---------------------------------------------------------------------------
- #define COMMAND_ERROR_ARI(MESSAGE, REPEAT) \
- { \
- int Result = CommandError(&E, MESSAGE, qaRetry | qaSkip | qaAbort); \
- switch (Result) { \
- case qaRetry: { REPEAT; } break; \
- case qaAbort: Abort(); \
- } \
- }
- #define FILE_OPERATION_LOOP_EX(ALLOW_SKIP, MESSAGE, OPERATION) \
- FILE_OPERATION_LOOP_CUSTOM(this, ALLOW_SKIP, MESSAGE, OPERATION)
- //---------------------------------------------------------------------------
- struct TMoveFileParams
- {
- AnsiString Target;
- AnsiString FileMask;
- };
- //---------------------------------------------------------------------------
- __fastcall TTerminal::TTerminal(): TSecureShell()
- {
- FFiles = new TRemoteDirectory(this);
- FExceptionOnFail = 0;
- FInTransaction = 0;
- FReadCurrentDirectoryPending = false;
- FReadDirectoryPending = false;
- FUsersGroupsLookedup = False;
- FGroups = new TUsersGroupsList();
- FUsers = new TUsersGroupsList();
- FOnProgress = NULL;
- FOnFinished = NULL;
- FOnDeleteLocalFile = NULL;
- FAdditionalInfo = NULL;
- FUseBusyCursor = True;
- FLockDirectory = "";
- FDirectoryCache = new TRemoteDirectoryCache();
- FDirectoryChangesCache = NULL;
- FFSProtocol = cfsUnknown;
- }
- //---------------------------------------------------------------------------
- __fastcall TTerminal::~TTerminal()
- {
- if (SessionData->CacheDirectoryChanges && SessionData->PreserveDirectoryChanges &&
- (FDirectoryChangesCache != NULL))
- {
- Configuration->SaveDirectoryChangesCache(SessionData->SessionKey,
- FDirectoryChangesCache);
- }
- SAFE_DESTROY(FFileSystem);
- delete FFiles;
- delete FGroups;
- delete FUsers;
- delete FDirectoryCache;
- delete FDirectoryChangesCache;
- delete FAdditionalInfo;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::KeepAlive()
- {
- if (SessionData->PingType == ptDummyCommand)
- {
- LogEvent("Executing dummy command to keep session alive.");
- assert(Active);
- assert(FFileSystem != NULL);
- try
- {
- FFileSystem->KeepAlive();
- }
- catch(Exception & E)
- {
- if (Active)
- {
- DoHandleExtendedException(&E);
- }
- else
- {
- throw;
- }
- }
- }
- else
- {
- TSecureShell::KeepAlive();
- }
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::IsAbsolutePath(const AnsiString Path)
- {
- return !Path.IsEmpty() && Path[1] == '/';
- }
- //---------------------------------------------------------------------------
- AnsiString __fastcall TTerminal::ExpandFileName(AnsiString Path,
- const AnsiString BasePath)
- {
- Path = UnixExcludeTrailingBackslash(Path);
- if (!IsAbsolutePath(Path) && !BasePath.IsEmpty())
- {
- // TODO: Handle more complicated cases like "../../xxx"
- if (Path == "..")
- {
- Path = UnixExcludeTrailingBackslash(UnixExtractFilePath(
- UnixExcludeTrailingBackslash(BasePath)));
- }
- else
- {
- Path = UnixIncludeTrailingBackslash(BasePath) + Path;
- }
- }
- return Path;
- }
- //---------------------------------------------------------------------------
- AnsiString __fastcall TTerminal::GetProtocolName()
- {
- assert(FFileSystem);
- return FFileSystem->ProtocolName;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::Close()
- {
- // file system cannot be destoryed here, moved to destructor
- TSecureShell::Close();
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::Open()
- {
- TSecureShell::Open();
- assert(!FFileSystem);
- if ((SessionData->FSProtocol == fsSCPonly) ||
- (SessionData->FSProtocol == fsSFTP && SshFallbackCmd()))
- {
- FFSProtocol = cfsSCP;
- FFileSystem = new TSCPFileSystem(this);
- LogEvent("Using SCP protocol.");
- }
- else
- {
- FFSProtocol = cfsSFTP;
- FFileSystem = new TSFTPFileSystem(this);
- LogEvent("Using SFTP protocol.");
- }
- if (SessionData->CacheDirectoryChanges)
- {
- FDirectoryChangesCache = new TRemoteDirectoryChangesCache();
- if (SessionData->PreserveDirectoryChanges)
- {
- Configuration->LoadDirectoryChangesCache(SessionData->SessionKey,
- FDirectoryChangesCache);
- }
- }
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::GetIsCapable(TFSCapability Capability) const
- {
- assert(FFileSystem);
- return FFileSystem->IsCapable(Capability);
- }
- //---------------------------------------------------------------------------
- TStrings * __fastcall TTerminal::GetAdditionalInfo()
- {
- bool Initial = (FAdditionalInfo == NULL);
- if (Initial)
- {
- FAdditionalInfo = new TStringList();
- }
- assert(FFileSystem);
- FFileSystem->AdditionalInfo(FAdditionalInfo, Initial);
- return FAdditionalInfo;
- }
- //---------------------------------------------------------------------------
- AnsiString __fastcall TTerminal::AbsolutePath(AnsiString Path)
- {
- return FFileSystem->AbsolutePath(Path);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ReactOnCommand(int /*TFSCommand*/ Cmd)
- {
- bool ChangesDirectory = false;
- bool ModifiesFiles = false;
- switch ((TFSCommand)Cmd) {
- case fsChangeDirectory:
- case fsHomeDirectory:
- ChangesDirectory = true;
- break;
- case fsCopyToRemote:
- case fsDeleteFile:
- case fsRenameFile:
- case fsMoveFile:
- case fsCreateDirectory:
- case fsChangeMode:
- case fsChangeGroup:
- case fsChangeOwner:
- case fsChangeProperties:
- case fsAnyCommand:
- ModifiesFiles = true;
- break;
- }
- if (ChangesDirectory)
- {
- if (!FInTransaction)
- {
- ReadCurrentDirectory();
- ReadDirectory(false);
- }
- else
- {
- FReadCurrentDirectoryPending = true;
- FReadDirectoryPending = true;
- }
- }
- else
- if (ModifiesFiles)
- {
- if (!FInTransaction) ReadDirectory(true);
- else FReadDirectoryPending = true;
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::TerminalError(AnsiString Msg)
- {
- TerminalError(NULL, Msg);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::TerminalError(Exception * E, AnsiString Msg)
- {
- throw ETerminal(E, Msg);
- }
- //---------------------------------------------------------------------------
- int __fastcall TTerminal::FileOperationLoop(TFileOperationEvent CallBackFunc,
- TFileOperationProgressType * OperationProgress, bool AllowSkip,
- const AnsiString Message, void * Param1, void * Param2)
- {
- assert(CallBackFunc);
- int Result;
- FILE_OPERATION_LOOP_EX
- (
- AllowSkip, Message,
- Result = CallBackFunc(Param1, Param2);
- );
- return Result;
- }
- //---------------------------------------------------------------------------
- AnsiString __fastcall TTerminal::TranslateLockedPath(AnsiString Path, bool Lock)
- {
- if (!SessionData->LockInHome || Path.IsEmpty() || (Path[1] != '/'))
- return Path;
- if (Lock)
- {
- if (Path.SubString(1, FLockDirectory.Length()) == FLockDirectory)
- {
- Path.Delete(1, FLockDirectory.Length());
- if (Path.IsEmpty()) Path = "/";
- }
- }
- else
- {
- Path = UnixExcludeTrailingBackslash(FLockDirectory + Path);
- }
- return Path;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ClearCaches()
- {
- FDirectoryCache->Clear();
- if (FDirectoryChangesCache != NULL)
- {
- FDirectoryChangesCache->Clear();
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ClearCachedFileList(const AnsiString Path,
- bool SubDirs)
- {
- FDirectoryCache->ClearFileList(Path, SubDirs);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::AddCachedFileList(TRemoteFileList * FileList)
- {
- FDirectoryCache->AddFileList(FileList);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::SetCurrentDirectory(AnsiString value)
- {
- assert(FFileSystem);
- value = TranslateLockedPath(value, false);
- if (value != FFileSystem->CurrentDirectory)
- {
- ChangeDirectory(value);
- }
- }
- //---------------------------------------------------------------------------
- AnsiString __fastcall TTerminal::GetCurrentDirectory()
- {
- if (FFileSystem)
- {
- FCurrentDirectory = FFileSystem->CurrentDirectory;
- if (FCurrentDirectory.IsEmpty())
- {
- ReadCurrentDirectory();
- }
- }
- return TranslateLockedPath(FCurrentDirectory, true);
- }
- //---------------------------------------------------------------------------
- AnsiString __fastcall TTerminal::PeekCurrentDirectory()
- {
- if (FFileSystem)
- {
- FCurrentDirectory = FFileSystem->CurrentDirectory;
- }
- return TranslateLockedPath(FCurrentDirectory, true);
- }
- //---------------------------------------------------------------------------
- TUsersGroupsList * __fastcall TTerminal::GetGroups()
- {
- assert(FFileSystem);
- if (!FUsersGroupsLookedup && SessionData->LookupUserGroups &&
- IsCapable[fcUserGroupListing])
- {
- LookupUsersGroups();
- }
- return FGroups;
- }
- //---------------------------------------------------------------------------
- TUsersGroupsList * __fastcall TTerminal::GetUsers()
- {
- assert(FFileSystem);
- if (!FUsersGroupsLookedup && SessionData->LookupUserGroups &&
- IsCapable[fcUserGroupListing])
- {
- LookupUsersGroups();
- }
- return FUsers;
- }
- //---------------------------------------------------------------------------
- AnsiString __fastcall TTerminal::GetUserName() const
- {
- // in future might be implemented to detect username similar to GetUserGroups
- return SessionData->UserName;
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::GetAreCachesEmpty() const
- {
- return FDirectoryCache->IsEmpty &&
- ((FDirectoryChangesCache == NULL) || FDirectoryChangesCache->IsEmpty);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoChangeDirectory()
- {
- if (FOnChangeDirectory)
- {
- FOnChangeDirectory(this);
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoReadDirectory(bool ReloadOnly)
- {
- if (FOnReadDirectory)
- {
- FOnReadDirectory(this, ReloadOnly);
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoStartReadDirectory()
- {
- if (FOnStartReadDirectory)
- {
- FOnStartReadDirectory(this);
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::BeginTransaction()
- {
- if (!FInTransaction)
- {
- FReadCurrentDirectoryPending = false;
- FReadDirectoryPending = false;
- }
- FInTransaction++;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::EndTransaction()
- {
- // it connection was closed due to fatal error during transaction, do nothing
- if (Active)
- {
- if (!FInTransaction)
- TerminalError("Can't end transaction, not in transaction");
- assert(FInTransaction > 0);
- FInTransaction--;
- if (FInTransaction == 0)
- {
- try
- {
- if (FReadCurrentDirectoryPending) ReadCurrentDirectory();
- if (FReadDirectoryPending) ReadDirectory(!FReadCurrentDirectoryPending);
- }
- __finally
- {
- FReadCurrentDirectoryPending = false;
- FReadDirectoryPending = false;
- }
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::SetExceptionOnFail(bool value)
- {
- if (value) FExceptionOnFail++;
- else
- {
- if (FExceptionOnFail == 0)
- throw Exception("ExceptionOnFail is already zero.");
- FExceptionOnFail--;
- }
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::GetExceptionOnFail() const
- {
- return (bool)(FExceptionOnFail > 0);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::CommandError(Exception * E, const AnsiString Msg)
- {
- CommandError(E, Msg, 0);
- }
- //---------------------------------------------------------------------------
- int __fastcall TTerminal::CommandError(Exception * E, const AnsiString Msg,
- int Answers)
- {
- int Result = 0;
- if (E && E->InheritsFrom(__classid(EFatal)))
- {
- FatalError(E, Msg);
- }
- else if (E && E->InheritsFrom(__classid(EAbort)))
- {
- // resent EAbort exception
- Abort();
- }
- else if (ExceptionOnFail)
- {
- throw ECommand(E, Msg);
- }
- else if (!Answers)
- {
- ECommand * ECmd = new ECommand(E, Msg);
- try
- {
- DoShowExtendedException(ECmd);
- }
- __finally
- {
- delete ECmd;
- }
- }
- else
- {
- Result = DoQueryUser(Msg, E, Answers, qpAllowContinueOnError);
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::HandleException(Exception * E)
- {
- if (ExceptionOnFail)
- {
- return false;
- }
- else
- {
- DoHandleExtendedException(E);
- return true;
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::CloseOnCompletion(const AnsiString Message)
- {
- LogEvent("Closing session after completed operation (as requested by user)");
- Close();
- throw ESshTerminate(NULL,
- Message.IsEmpty() ? LoadStr(CLOSED_ON_COMPLETION) : Message);
- }
- //---------------------------------------------------------------------------
- int __fastcall TTerminal::ConfirmFileOverwrite(const AnsiString FileName,
- const TOverwriteFileParams * FileParams, int Answers, int Params,
- TOperationSide Side)
- {
- AnsiString Message = FMTLOAD((Side == osLocal ? LOCAL_FILE_OVERWRITE :
- REMOTE_FILE_OVERWRITE), (FileName));
- if (FileParams)
- {
- Message = FMTLOAD(FILE_OVERWRITE_DETAILS, (Message,
- IntToStr(FileParams->SourceSize),
- FormatDateTime("ddddd tt", FileParams->SourceTimestamp),
- IntToStr(FileParams->DestSize),
- FormatDateTime("ddddd tt", FileParams->DestTimestamp)));
- }
- return DoQueryUser(Message, Answers, Params);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::FileModified(const TRemoteFile * File,
- const AnsiString FileName)
- {
- if (SessionData->CacheDirectories)
- {
- if ((File != NULL) && (File->Directory != NULL))
- {
- if (File->IsDirectory)
- {
- // do not use UnixIncludeTrailingBackslash(CurrentDirectory)
- DirectoryModified(
- File->Directory->FullDirectory + File->FileName, true);
- }
- DirectoryModified(File->Directory->Directory, false);
- }
- else if (!FileName.IsEmpty())
- {
- AnsiString Directory = UnixExtractFilePath(FileName);
- DirectoryModified(
- !Directory.IsEmpty() ? Directory : CurrentDirectory, false);
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoDirectoryModified(const AnsiString Path, bool SubDirs)
- {
- if (OnDirectoryModified != NULL)
- {
- OnDirectoryModified(this, Path, SubDirs);
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DirectoryModified(const AnsiString Path, bool SubDirs)
- {
- ClearCachedFileList(Path, SubDirs);
- DoDirectoryModified(Path, SubDirs);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DirectoryLoaded(TRemoteFileList * FileList)
- {
- AddCachedFileList(FileList);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ReloadDirectory()
- {
- if (SessionData->CacheDirectories)
- {
- DirectoryModified(CurrentDirectory, false);
- }
- if (SessionData->CacheDirectoryChanges)
- {
- assert(FDirectoryChangesCache != NULL);
- FDirectoryChangesCache->ClearDirectoryChange(CurrentDirectory);
- }
- ReadCurrentDirectory();
- FReadCurrentDirectoryPending = false;
- ReadDirectory(true);
- FReadDirectoryPending = false;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::RefreshDirectory()
- {
- if (SessionData->CacheDirectories &&
- FDirectoryCache->HasNewerFileList(CurrentDirectory, FFiles->Timestamp))
- {
- // Second parameter was added to allow (rather force) using the cache.
- // Before, the directory was reloaded always, it seems useless,
- // has it any reason?
- ReadDirectory(true, true);
- FReadDirectoryPending = false;
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::EnsureNonExistence(const AnsiString FileName)
- {
- // if filename doesn't contain path, we check for existence of file
- if ((UnixExtractFileDir(FileName).IsEmpty()) &&
- UnixComparePaths(CurrentDirectory, FFiles->Directory))
- {
- TRemoteFile *File = FFiles->FindFile(FileName);
- if (File)
- {
- if (File->IsDirectory) throw ECommand(NULL, FMTLOAD(RENAME_CREATE_DIR_EXISTS, (FileName)));
- else throw ECommand(NULL, FMTLOAD(RENAME_CREATE_FILE_EXISTS, (FileName)));
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoStartup()
- {
- LogEvent("Doing startup conversation with host.");
- BeginTransaction();
- try
- {
- UpdateStatus(sshStartup);
- // Make sure that directory would be loaded at last
- FReadCurrentDirectoryPending = true;
- FReadDirectoryPending = true;
- FFileSystem->DoStartup();
- if (SessionData->LookupUserGroups && IsCapable[fcUserGroupListing])
- {
- LookupUsersGroups();
- }
- UpdateStatus(sshOpenDirectory);
- if (!SessionData->RemoteDirectory.IsEmpty())
- {
- ChangeDirectory(SessionData->RemoteDirectory);
- }
- }
- __finally
- {
- EndTransaction();
- }
- LogEvent("Startup conversation with host finished.");
- UpdateStatus(sshReady);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ReadCurrentDirectory()
- {
- assert(FFileSystem);
- try
- {
- LogEvent("Getting current directory name.");
- AnsiString OldDirectory = FFileSystem->CurrentDirectory;
- FFileSystem->ReadCurrentDirectory();
- ReactOnCommand(fsCurrentDirectory);
- if (SessionData->CacheDirectoryChanges)
- {
- assert(FDirectoryChangesCache != NULL);
- FDirectoryChangesCache->AddDirectoryChange(OldDirectory,
- FLastDirectoryChange, CurrentDirectory);
- }
- if (OldDirectory.IsEmpty())
- {
- FLockDirectory = (SessionData->LockInHome ?
- FFileSystem->CurrentDirectory : AnsiString(""));
- }
- if (OldDirectory != FFileSystem->CurrentDirectory) DoChangeDirectory();
- }
- catch (Exception &E)
- {
- CommandError(&E, LoadStr(READ_CURRENT_DIR_ERROR));
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ReadDirectory(bool ReloadOnly, bool ForceCache)
- {
- bool LoadedFromCache = false;
- if (SessionData->CacheDirectories && FDirectoryCache->HasFileList(CurrentDirectory))
- {
- if (ReloadOnly && !ForceCache)
- {
- LogEvent("Cached directory not reloaded.");
- }
- else
- {
- DoStartReadDirectory();
- try
- {
- LoadedFromCache = FDirectoryCache->GetFileList(CurrentDirectory, FFiles);
- }
- __finally
- {
- DoReadDirectory(ReloadOnly);
- }
- if (LoadedFromCache)
- {
- LogEvent("Directory content loaded from cache.");
- }
- else
- {
- LogEvent("Cached Directory content has been removed.");
- }
- }
- }
- if (!LoadedFromCache)
- {
- DoStartReadDirectory();
- FFiles->Directory = CurrentDirectory;
- try
- {
- try
- {
- CustomReadDirectory(FFiles);
- }
- __finally
- {
- // this must be called before error is displayed, otherwise
- // TUnixDirView would be drawn with invalid data (it keeps reference
- // to already destoroyed old listing)
- DoReadDirectory(ReloadOnly);
- if (Active)
- {
- if (SessionData->CacheDirectories)
- {
- DirectoryLoaded(FFiles);
- }
- }
- }
- }
- catch (Exception &E)
- {
- CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FFiles->Directory))));
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::CustomReadDirectory(TRemoteFileList * FileList)
- {
- assert(FileList);
- assert(FFileSystem);
- FFileSystem->ReadDirectory(FileList);
- ReactOnCommand(fsListDirectory);
- }
- //---------------------------------------------------------------------------
- TRemoteFileList * TTerminal::ReadDirectoryListing(AnsiString Directory)
- {
- TRemoteFileList * FileList;
- try
- {
- FileList = new TRemoteFileList();
- try
- {
- FileList->Directory = Directory;
- AnsiString Directory = UnixIncludeTrailingBackslash(Directory);
- ExceptionOnFail = true;
- try
- {
- ReadDirectory(FileList);
- }
- __finally
- {
- ExceptionOnFail = false;
- }
- }
- catch(...)
- {
- delete FileList;
- FileList = NULL;
- throw;
- }
- }
- catch(Exception & E)
- {
- COMMAND_ERROR_ARI
- (
- "",
- FileList = ReadDirectoryListing(Directory);
- );
- }
- return FileList;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ProcessDirectory(const AnsiString DirName,
- TProcessFileEvent CallBackFunc, void * Param)
- {
- TRemoteFileList * FileList = ReadDirectoryListing(DirName);
- // skip if directory listing fails and user selects "skip"
- if (FileList)
- {
- try
- {
- AnsiString Directory = UnixIncludeTrailingBackslash(DirName);
- TRemoteFile * File;
- for (int Index = 0; Index < FileList->Count; Index++)
- {
- File = FileList->Files[Index];
- if (!File->IsParentDirectory && !File->IsThisDirectory)
- {
- CallBackFunc(Directory + File->FileName, File, Param);
- }
- }
- }
- __finally
- {
- delete FileList;
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ReadDirectory(TRemoteFileList * FileList)
- {
- try
- {
- CustomReadDirectory(FileList);
- }
- catch (Exception &E)
- {
- CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FileList->Directory))));
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ReadSymlink(TRemoteFile * SymlinkFile,
- TRemoteFile *& File)
- {
- assert(FFileSystem);
- try
- {
- LogEvent(FORMAT("Reading symlink \"%s\".", (SymlinkFile->FileName)));
- FFileSystem->ReadSymlink(SymlinkFile, File);
- ReactOnCommand(fsReadSymlink);
- }
- catch (Exception &E)
- {
- CommandError(&E, FMTLOAD(READ_SYMLINK_ERROR, (SymlinkFile->FileName)));
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ReadFile(const AnsiString FileName,
- TRemoteFile *& File)
- {
- assert(FFileSystem);
- File = NULL;
- try
- {
- LogEvent(FORMAT("Listing file \"%s\".", (FileName)));
- FFileSystem->ReadFile(FileName, File);
- ReactOnCommand(fsListFile);
- }
- catch (Exception &E)
- {
- if (File) delete File;
- File = NULL;
- CommandError(&E, FMTLOAD(LIST_DIR_ERROR, (FileName)));
- }
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::ProcessFiles(TStrings * FileList,
- TFileOperation Operation, TProcessFileEvent ProcessFile, void * Param,
- TOperationSide Side)
- {
- assert(FFileSystem);
- assert(FileList);
- bool Result = false;
- bool DisconnectWhenComplete = false;
- try
- {
- TFileOperationProgressType Progress(FOnProgress, FOnFinished);
- Progress.Start(Operation, Side, FileList->Count);
- FOperationProgress = &Progress;
- try
- {
- BeginTransaction();
- try
- {
- int Index = 0;
- AnsiString FileName;
- bool Success;
- while ((Index < FileList->Count) && (Progress.Cancel == csContinue))
- {
- FileName = FileList->Strings[Index];
- try
- {
- Success = false;
- ProcessFile(FileName, (TRemoteFile *)FileList->Objects[Index], Param);
- Success = true;
- }
- __finally
- {
- Progress.Finish(FileName, Success, DisconnectWhenComplete);
- }
- Index++;
- }
- }
- __finally
- {
- EndTransaction();
- }
- if (Progress.Cancel == csContinue)
- {
- Result = true;
- }
- }
- __finally
- {
- FOperationProgress = NULL;
- Progress.Stop();
- }
- }
- catch (...)
- {
- DisconnectWhenComplete = false;
- // this was missing here. was it by purpose?
- // without it any error message is lost
- throw;
- }
- if (DisconnectWhenComplete)
- {
- CloseOnCompletion();
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DeleteFile(AnsiString FileName,
- const TRemoteFile * File, void * Recursive)
- {
- if (FileName.IsEmpty() && File)
- {
- FileName = File->FileName;
- }
- if (OperationProgress && OperationProgress->Operation == foDelete)
- {
- if (OperationProgress->Cancel != csContinue) Abort();
- OperationProgress->SetFile(FileName);
- }
- LogEvent(FORMAT("Deleting file \"%s\".", (FileName)));
- if (File) FileModified(File, FileName);
- DoDeleteFile(FileName, File, Recursive);
- ReactOnCommand(fsDeleteFile);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoDeleteFile(const AnsiString FileName,
- const TRemoteFile * File, void * Recursive)
- {
- try
- {
- assert(FFileSystem);
- // 'File' parameter: SFTPFileSystem needs to know if file is file or directory
- FFileSystem->DeleteFile(FileName, File,
- Recursive ? *((bool*)Recursive) : true);
- }
- catch(Exception & E)
- {
- COMMAND_ERROR_ARI
- (
- FMTLOAD(DELETE_FILE_ERROR, (FileName)),
- DoDeleteFile(FileName, File, Recursive)
- );
- }
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::DeleteFiles(TStrings * FilesToDelete, bool * Recursive)
- {
- return ProcessFiles(FilesToDelete, foDelete, DeleteFile, Recursive);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DeleteLocalFile(AnsiString FileName,
- const TRemoteFile * /*File*/, void * /*Param*/)
- {
- if (OnDeleteLocalFile == NULL)
- {
- if (!RecursiveDeleteFile(FileName, false))
- {
- throw Exception(FMTLOAD(DELETE_FILE_ERROR, (FileName)));
- }
- }
- else
- {
- OnDeleteLocalFile(FileName);
- }
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::DeleteLocalFiles(TStrings * FileList)
- {
- return ProcessFiles(FileList, foDelete, DeleteLocalFile, NULL, osLocal);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::CustomCommandOnFile(AnsiString FileName,
- const TRemoteFile * File, void * AParams)
- {
- TCustomCommandParams * Params = ((TCustomCommandParams *)AParams);
- if (FileName.IsEmpty() && File)
- {
- FileName = File->FileName;
- }
- if (OperationProgress && OperationProgress->Operation == foCustomCommand)
- {
- if (OperationProgress->Cancel != csContinue) Abort();
- OperationProgress->SetFile(FileName);
- }
- LogEvent(FORMAT("Executing custom command \"%s\" (%d) on file \"%s\".",
- (Params->Command, Params->Params, FileName)));
- if (File) FileModified(File, FileName);
- DoCustomCommandOnFile(FileName, File, Params->Command, Params->Params);
- ReactOnCommand(fsAnyCommand);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoCustomCommandOnFile(AnsiString FileName,
- const TRemoteFile * File, AnsiString Command, int Params)
- {
- try
- {
- assert(FFileSystem);
- FFileSystem->CustomCommandOnFile(FileName, File, Command, Params);
- }
- catch(Exception & E)
- {
- COMMAND_ERROR_ARI
- (
- FMTLOAD(CUSTOM_COMMAND_ERROR, (Command, FileName)),
- DoCustomCommandOnFile(FileName, File, Command, Params)
- );
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::CustomCommandOnFiles(AnsiString Command,
- int Params, TStrings * Files)
- {
- TCustomCommandParams AParams;
- AParams.Command = Command;
- AParams.Params = Params;
- ProcessFiles(Files, foCustomCommand, CustomCommandOnFile, &AParams);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ChangeFileProperties(AnsiString FileName,
- const TRemoteFile * File, /*const TRemoteProperties*/ void * Properties)
- {
- TRemoteProperties * RProperties = (TRemoteProperties *)Properties;
- assert(RProperties && !RProperties->Valid.Empty());
- if (FileName.IsEmpty() && File)
- {
- FileName = File->FileName;
- }
- if (OperationProgress && OperationProgress->Operation == foSetProperties)
- {
- if (OperationProgress->Cancel != csContinue) Abort();
- OperationProgress->SetFile(FileName);
- }
- if (IsLogging())
- {
- LogEvent(FORMAT("Changing properties of \"%s\" (%s)",
- (FileName, BooleanToEngStr(RProperties->Recursive))));
- if (RProperties->Valid.Contains(vpRights))
- {
- LogEvent(FORMAT(" - mode: \"%s\"", (RProperties->Rights.ModeStr)));
- }
- if (RProperties->Valid.Contains(vpGroup))
- {
- LogEvent(FORMAT(" - group: \"%s\"", (RProperties->Group)));
- }
- if (RProperties->Valid.Contains(vpOwner))
- {
- LogEvent(FORMAT(" - owner: \"%s\"", (RProperties->Owner)));
- }
- }
- if (File) FileModified(File, FileName);
- DoChangeFileProperties(FileName, File, RProperties);
- ReactOnCommand(fsChangeProperties);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoChangeFileProperties(const AnsiString FileName,
- const TRemoteFile * File, const TRemoteProperties * Properties)
- {
- try
- {
- assert(FFileSystem);
- FFileSystem->ChangeFileProperties(FileName, File, Properties);
- }
- catch(Exception & E)
- {
- COMMAND_ERROR_ARI
- (
- FMTLOAD(CHANGE_PROPERTIES_ERROR, (FileName)),
- DoChangeFileProperties(FileName, File, Properties)
- );
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ChangeFilesProperties(TStrings * FileList,
- const TRemoteProperties * Properties)
- {
- ProcessFiles(FileList, foSetProperties, ChangeFileProperties, (void *)Properties);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::CalculateFileSize(AnsiString FileName,
- const TRemoteFile * File, /*TCalculateSizeParams*/ void * Param)
- {
- assert(Param);
- assert(File);
- if (FileName.IsEmpty() && File)
- {
- FileName = File->FileName;
- }
- if (File->IsDirectory && !File->IsSymLink)
- {
- LogEvent(FORMAT("Getting size of directory \"%s\"", (FileName)));
- DoCalculateDirectorySize(FileName, File,
- static_cast<TCalculateSizeParams*>(Param));
- }
- else
- {
- static_cast<TCalculateSizeParams*>(Param)->Size += File->Size;
- }
- if (OperationProgress && OperationProgress->Operation == foCalculateSize)
- {
- if (OperationProgress->Cancel != csContinue) Abort();
- OperationProgress->SetFile(FileName);
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoCalculateDirectorySize(const AnsiString FileName,
- const TRemoteFile * File, TCalculateSizeParams * Params)
- {
- try
- {
- ProcessDirectory(FileName, CalculateFileSize, Params);
- }
- catch(Exception & E)
- {
- if (!Active || ((Params->Params & csIgnoreErrors) == 0))
- {
- COMMAND_ERROR_ARI
- (
- FMTLOAD(CALCULATE_SIZE_ERROR, (FileName)),
- DoCalculateDirectorySize(FileName, File, Params)
- );
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::CalculateFilesSize(TStrings * FileList,
- __int64 & Size, int Params)
- {
- TCalculateSizeParams Param;
- Param.Size = 0;
- Param.Params = Params;
- ProcessFiles(FileList, foCalculateSize, CalculateFileSize, &Param);
- Size = Param.Size;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::RenameFile(const AnsiString FileName,
- const AnsiString NewName)
- {
- LogEvent(FORMAT("Renaming file \"%s\" to \"%s\".", (FileName, NewName)));
- DoRenameFile(FileName, NewName, false);
- ReactOnCommand(fsRenameFile);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::RenameFile(const TRemoteFile * File,
- const AnsiString NewName, bool CheckExistence)
- {
- assert(File && File->Directory == FFiles);
- bool Proceed = true;
- // if filename doesn't contain path, we check for existence of file
- if ((File->FileName != NewName) && CheckExistence &&
- Configuration->ConfirmOverwriting &&
- UnixComparePaths(CurrentDirectory, FFiles->Directory))
- {
- TRemoteFile * DuplicateFile = FFiles->FindFile(NewName);
- if (DuplicateFile)
- {
- AnsiString QuestionFmt;
- if (DuplicateFile->IsDirectory) QuestionFmt = LoadStr(DIRECTORY_OVERWRITE);
- else QuestionFmt = LoadStr(FILE_OVERWRITE);
- int Result;
- Result = DoQueryUser(FORMAT(QuestionFmt, (NewName)),
- qaYes | qaNo, qpNeverAskAgainCheck);
- if (Result == qaNeverAskAgain)
- {
- Proceed = true;
- Configuration->ConfirmOverwriting = false;
- }
- else
- {
- Proceed = (Result == qaYes);
- }
- }
- }
- if (Proceed)
- {
- FileModified(File, File->FileName);
- RenameFile(File->FileName, NewName);
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoRenameFile(const AnsiString FileName,
- const AnsiString NewName, bool Move)
- {
- try
- {
- assert(FFileSystem);
- FFileSystem->RenameFile(FileName, NewName);
- }
- catch(Exception & E)
- {
- COMMAND_ERROR_ARI
- (
- FMTLOAD(Move ? MOVE_FILE_ERROR : RENAME_FILE_ERROR, (FileName, NewName)),
- DoRenameFile(FileName, NewName, Move)
- );
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::MoveFile(const AnsiString FileName,
- const TRemoteFile * File, /*const TMoveFileParams*/ void * Param)
- {
- if (OperationProgress && (OperationProgress->Operation == foRemoteMove))
- {
- if (OperationProgress->Cancel != csContinue) Abort();
- OperationProgress->SetFile(FileName);
- }
- assert(Param != NULL);
- const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
- AnsiString NewName = UnixIncludeTrailingBackslash(Params.Target) +
- MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
- LogEvent(FORMAT("Moving file \"%s\" to \"%s\".", (FileName, NewName)));
- FileModified(File, FileName);
- DoRenameFile(FileName, NewName, true);
- ReactOnCommand(fsMoveFile);
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::MoveFiles(TStrings * FileList, const AnsiString Target,
- const AnsiString FileMask)
- {
- TMoveFileParams Params;
- Params.Target = Target;
- Params.FileMask = FileMask;
- DirectoryModified(Target, true);
- return ProcessFiles(FileList, foRemoteMove, MoveFile, &Params);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::CreateDirectory(const AnsiString DirName,
- const TRemoteProperties * Properties)
- {
- assert(FFileSystem);
- EnsureNonExistence(DirName);
- FileModified(NULL, DirName);
- LogEvent(FORMAT("Creating directory \"%s\".", (DirName)));
- DoCreateDirectory(DirName, Properties);
- ReactOnCommand(fsCreateDirectory);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoCreateDirectory(const AnsiString DirName,
- const TRemoteProperties * Properties)
- {
- try
- {
- assert(FFileSystem);
- FFileSystem->CreateDirectory(DirName, Properties);
- }
- catch(Exception & E)
- {
- COMMAND_ERROR_ARI
- (
- FMTLOAD(CREATE_DIR_ERROR, (DirName)),
- DoCreateDirectory(DirName, Properties)
- );
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::CreateLink(const AnsiString FileName,
- const AnsiString PointTo, bool Symbolic)
- {
- assert(FFileSystem);
- EnsureNonExistence(FileName);
- if (SessionData->CacheDirectories)
- {
- DirectoryModified(CurrentDirectory, false);
- }
- LogEvent(FORMAT("Creating link \"%s\" to \"%s\" (symbolic: %s).",
- (FileName, PointTo, BooleanToEngStr(Symbolic))));
- DoCreateLink(FileName, PointTo, Symbolic);
- ReactOnCommand(fsCreateDirectory);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoCreateLink(const AnsiString FileName,
- const AnsiString PointTo, bool Symbolic)
- {
- try
- {
- assert(FFileSystem);
- FFileSystem->CreateLink(FileName, PointTo, Symbolic);
- }
- catch(Exception & E)
- {
- COMMAND_ERROR_ARI
- (
- FMTLOAD(CREATE_LINK_ERROR, (FileName)),
- DoCreateLink(FileName, PointTo, Symbolic);
- );
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::HomeDirectory()
- {
- assert(FFileSystem);
- try
- {
- LogEvent("Changing directory to home directory.");
- FFileSystem->HomeDirectory();
- ReactOnCommand(fsHomeDirectory);
- }
- catch (Exception &E)
- {
- CommandError(&E, LoadStr(CHANGE_HOMEDIR_ERROR));
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::ChangeDirectory(const AnsiString Directory)
- {
- assert(FFileSystem);
- try
- {
- AnsiString CachedDirectory;
- assert(!SessionData->CacheDirectoryChanges || (FDirectoryChangesCache != NULL));
- if (SessionData->CacheDirectoryChanges &&
- FDirectoryChangesCache->GetDirectoryChange(PeekCurrentDirectory(),
- Directory, CachedDirectory))
- {
- LogEvent(FORMAT("Cached directory change via \"%s\" to \"%s\".",
- (Directory, CachedDirectory)));
- FFileSystem->CachedChangeDirectory(CachedDirectory);
- }
- else
- {
- LogEvent(FORMAT("Changing directory to \"%s\".", (Directory)));
- FFileSystem->ChangeDirectory(Directory);
- }
- FLastDirectoryChange = Directory;
- ReactOnCommand(fsChangeDirectory);
- }
- catch (Exception &E)
- {
- CommandError(&E, FMTLOAD(CHANGE_DIR_ERROR, (Directory)));
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::LookupUsersGroups()
- {
- assert(FFileSystem);
- assert(IsCapable[fcUserGroupListing]);
- try
- {
- FUsersGroupsLookedup = true;
- LogEvent("Looking up groups and users.");
- FFileSystem->LookupUsersGroups();
- ReactOnCommand(fsLookupUsersGroups);
- if (IsLogging())
- {
- if (FGroups->Count > 0)
- {
- LogEvent("Following groups found:");
- for (int Index = 0; Index < FGroups->Count; Index++)
- {
- LogEvent(AnsiString(" ") + FGroups->Strings[Index]);
- }
- }
- else
- {
- LogEvent("No groups found.");
- }
- if (FUsers->Count > 0)
- {
- LogEvent("Following users found:");
- for (int Index = 0; Index < FUsers->Count; Index++)
- {
- LogEvent(AnsiString(" ") + FUsers->Strings[Index]);
- }
- }
- else
- {
- LogEvent("No users found.");
- }
- }
- }
- catch (Exception &E)
- {
- CommandError(&E, LoadStr(LOOKUP_GROUPS_ERROR));
- }
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::AllowedAnyCommand(const AnsiString Command)
- {
- return !Command.Trim().IsEmpty();
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::AnyCommand(const AnsiString Command)
- {
- assert(FFileSystem);
- try
- {
- DirectoryModified(CurrentDirectory, false);
- LogEvent("Executing used defined command.");
- FFileSystem->AnyCommand(Command);
- ReactOnCommand(fsAnyCommand);
- }
- catch (Exception &E)
- {
- if (ExceptionOnFail || (E.InheritsFrom(__classid(EFatal)))) throw;
- else DoShowExtendedException(&E);
- }
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::CreateLocalFile(const AnsiString FileName,
- TFileOperationProgressType * OperationProgress, HANDLE * AHandle)
- {
- assert(AHandle);
- bool Result = true;
- FILE_OPERATION_LOOP (FMTLOAD(CREATE_FILE_ERROR, (FileName)),
- bool Done;
- do
- {
- *AHandle = CreateFile(FileName.c_str(), GENERIC_WRITE, FILE_SHARE_READ,
- NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
- Done = (*AHandle != INVALID_HANDLE_VALUE);
- if (!Done)
- {
- int FileAttr;
- if (FileExists(FileName) &&
- (((FileAttr = FileGetAttr(FileName)) & faReadOnly) != 0))
- {
- if (OperationProgress->NoToAll)
- {
- Result = false;
- }
- else if (!OperationProgress->YesToAll)
- {
- int Answer;
- SUSPEND_OPERATION
- (
- Answer = DoQueryUser(
- FMTLOAD(READ_ONLY_OVERWRITE, (FileName)),
- qaYes | qaNo | qaAbort | qaYesToAll | qaNoToAll, 0);
- );
- switch (Answer) {
- case qaYesToAll: OperationProgress->YesToAll = true; break;
- case qaAbort: OperationProgress->Cancel = csCancel; // continue on next case
- case qaNoToAll: OperationProgress->NoToAll = true;
- case qaNo: Result = false; break;
- }
- }
- if (Result)
- {
- FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (FileName)),
- if (FileSetAttr(FileName, FileAttr & ~faReadOnly) != 0)
- {
- EXCEPTION;
- }
- );
- }
- else
- {
- Done = true;
- }
- }
- else
- {
- EXCEPTION;
- }
- }
- }
- while (!Done);
- );
- return Result;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::OpenLocalFile(const AnsiString FileName,
- int Access, int * AAttrs, HANDLE * AHandle, unsigned long * ACTime,
- unsigned long * AMTime, unsigned long * AATime, __int64 * ASize,
- bool TryWriteReadOnly)
- {
- int Attrs = 0;
- HANDLE Handle = 0;
- FILE_OPERATION_LOOP (FMTLOAD(FILE_NOT_EXISTS, (FileName)),
- Attrs = FileGetAttr(FileName);
- if (Attrs == -1) EXCEPTION;
- )
- if ((Attrs & faDirectory) == 0)
- {
- bool NoHandle = false;
- if (!TryWriteReadOnly && (Access == GENERIC_WRITE) &&
- ((Attrs & faReadOnly) != 0))
- {
- Access = GENERIC_READ;
- NoHandle = true;
- }
- FILE_OPERATION_LOOP (FMTLOAD(OPENFILE_ERROR, (FileName)),
- Handle = CreateFile(FileName.c_str(), Access,
- Access == GENERIC_READ ? FILE_SHARE_READ | FILE_SHARE_WRITE : FILE_SHARE_READ,
- NULL, OPEN_EXISTING, 0, 0);
- if (Handle == INVALID_HANDLE_VALUE)
- {
- Handle = 0;
- EXCEPTION;
- }
- );
- try
- {
- if (AATime || AMTime || ACTime)
- {
- // Get last file access and modification time
- FILE_OPERATION_LOOP (FMTLOAD(CANT_GET_ATTRS, (FileName)),
- FILETIME ATime;
- FILETIME MTime;
- FILETIME CTime;
- if (!GetFileTime(Handle, &CTime, &ATime, &MTime)) EXCEPTION;
- if (ACTime)
- {
- *ACTime = ConvertTimestampToUnix(CTime, SessionData->ConsiderDST);
- }
- if (AATime)
- {
- *AATime = ConvertTimestampToUnix(ATime, SessionData->ConsiderDST);
- }
- if (AMTime)
- {
- *AMTime = ConvertTimestampToUnix(MTime, SessionData->ConsiderDST);
- }
- );
- }
- if (ASize)
- {
- // Get file size
- FILE_OPERATION_LOOP (FMTLOAD(CANT_GET_ATTRS, (FileName)),
- unsigned long LSize;
- unsigned long HSize;
- LSize = GetFileSize(Handle, &HSize);
- if ((LSize == 0xFFFFFFFF) && (GetLastError() != NO_ERROR)) EXCEPTION;
- *ASize = (__int64(HSize) << 32) + LSize;
- );
- }
- if ((AHandle == NULL) || NoHandle)
- {
- CloseHandle(Handle);
- Handle = NULL;
- }
- }
- catch(...)
- {
- CloseHandle(Handle);
- throw;
- }
- }
- if (AAttrs) *AAttrs = Attrs;
- if (AHandle) *AHandle = Handle;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::CalculateLocalFileSize(const AnsiString FileName,
- const TSearchRec Rec, /*__int64*/ void * Size)
- {
- if ((Rec.Attr & faDirectory) == 0)
- {
- (*static_cast<__int64*>(Size)) +=
- (static_cast<__int64>(Rec.FindData.nFileSizeHigh) << 32) +
- Rec.FindData.nFileSizeLow;
- }
- if (OperationProgress && OperationProgress->Operation == foCalculateSize)
- {
- if (OperationProgress->Cancel != csContinue) Abort();
- OperationProgress->SetFile(FileName);
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::CalculateLocalFilesSize(TStrings * FileList, __int64 & Size)
- {
- Size = 0;
- TFileOperationProgressType OperationProgress(FOnProgress, FOnFinished);
- OperationProgress.Start(foCalculateSize, osLocal, FileList->Count);
- try
- {
- assert(!FOperationProgress);
- FOperationProgress = &OperationProgress;
- TSearchRec Rec;
- for (int Index = 0; Index < FileList->Count; Index++)
- {
- if (FileSearchRec(FileList->Strings[Index], Rec))
- {
- if (Rec.Attr & faDirectory)
- {
- ProcessLocalDirectory(FileList->Strings[Index],
- CalculateLocalFileSize, &Size);
- }
- CalculateLocalFileSize(FileList->Strings[Index], Rec, &Size);
- }
- }
- }
- __finally
- {
- FOperationProgress = NULL;
- OperationProgress.Stop();
- }
- }
- //---------------------------------------------------------------------------
- struct TSynchronizeFileData
- {
- int Time;
- int Attr;
- unsigned long SizeHigh;
- unsigned long SizeLow;
- FILETIME LastWriteTime;
- bool Modified;
- bool New;
- };
- //---------------------------------------------------------------------------
- struct TSynchronizeData
- {
- AnsiString LocalDirectory;
- AnsiString RemoteDirectory;
- TTerminal::TSynchronizeMode Mode;
- int Params;
- TSynchronizeDirectory OnSynchronizeDirectory;
- TStringList * LocalFileList;
- TStringList * ModifiedRemoteFileList;
- TStringList * NewRemoteFileList;
- const TCopyParamType * CopyParam;
- };
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::Synchronize(const AnsiString LocalDirectory,
- const AnsiString RemoteDirectory, TSynchronizeMode Mode,
- const TCopyParamType * CopyParam, int Params,
- TSynchronizeDirectory OnSynchronizeDirectory)
- {
- assert(CopyParam != NULL);
- TCopyParamType SyncCopyParam = *CopyParam;
- SyncCopyParam.PreserveTime = true;
- BeginTransaction();
- try
- {
- DoSynchronizeDirectory(LocalDirectory, RemoteDirectory, Mode,
- &SyncCopyParam, Params, OnSynchronizeDirectory);
- }
- __finally
- {
- EndTransaction();
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::DoSynchronizeDirectory(const AnsiString LocalDirectory,
- const AnsiString RemoteDirectory, TSynchronizeMode Mode,
- const TCopyParamType * CopyParam, int Params,
- TSynchronizeDirectory OnSynchronizeDirectory)
- {
- TSearchRec SearchRec;
- bool Found;
- bool Delete = (Params & spDelete) != 0;
- TSynchronizeData Data;
- Data.LocalDirectory = IncludeTrailingBackslash(LocalDirectory);
- Data.RemoteDirectory = UnixIncludeTrailingBackslash(RemoteDirectory);
- Data.Mode = Mode;
- Data.Params = Params;
- Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
- Data.LocalFileList = NULL;
- Data.NewRemoteFileList = NULL;
- Data.ModifiedRemoteFileList = NULL;
- Data.CopyParam = CopyParam;
- TStrings * LocalFileList = NULL;
- LogEvent(FORMAT("Synchronizing local directory '%s' with remote directory '%s', "
- "mode = %d, params = %d", (LocalDirectory, RemoteDirectory,
- int(Mode), int(Params))));
- bool Continue = true;
- OnSynchronizeDirectory(LocalDirectory, RemoteDirectory, Continue);
- if (!Continue)
- {
- Abort();
- }
- try
- {
- Data.LocalFileList = new TStringList();
- Data.LocalFileList->Sorted = true;
- Data.LocalFileList->CaseSensitive = false;
- Data.NewRemoteFileList = new TStringList();
- Data.ModifiedRemoteFileList = new TStringList();
- LocalFileList = new TStringList();
- FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (LocalDirectory)),
- int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
- Found = (FindFirst(Data.LocalDirectory + "*.*", FindAttrs, SearchRec) == 0);
- );
- if (Found)
- {
- try
- {
- AnsiString FileName;
- while (Found)
- {
- FileName = SearchRec.Name;
- if ((FileName != ".") && (FileName != ".."))
- {
- TSynchronizeFileData * FileData = new TSynchronizeFileData;
- FileData->Time = SearchRec.Time;
- FileData->SizeHigh = SearchRec.FindData.nFileSizeHigh;
- FileData->SizeLow = SearchRec.FindData.nFileSizeLow;
- FileData->Attr = SearchRec.Attr;
- FileData->LastWriteTime = SearchRec.FindData.ftLastWriteTime;
- FileData->New = true;
- FileData->Modified = false;
- Data.LocalFileList->AddObject(FileName,
- reinterpret_cast<TObject*>(FileData));
- }
- FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (LocalDirectory)),
- Found = (FindNext(SearchRec) == 0);
- );
- }
- }
- __finally
- {
- FindClose(SearchRec);
- }
- ProcessDirectory(RemoteDirectory, SynchronizeFile, &Data);
- TSynchronizeFileData * FileData;
- for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
- {
- FileData = reinterpret_cast<TSynchronizeFileData *>
- (Data.LocalFileList->Objects[Index]);
- if ((FileData->Modified && ((Mode == smBoth) || (Mode == smRemote))) ||
- (FileData->New))
- {
- LocalFileList->Add(Data.LocalDirectory + Data.LocalFileList->Strings[Index]);
- }
- }
- int CopyParams = (Params & spNoConfirmation) != 0 ? cpNoConfirmation : 0;
- if (LocalFileList->Count > 0)
- {
- bool Result;
- if ((Mode == smBoth) || (Mode == smRemote))
- {
- Result = CopyToRemote(LocalFileList, RemoteDirectory, CopyParam, CopyParams);
- }
- else if ((Mode == smLocal) && Delete)
- {
- Result = DeleteLocalFiles(LocalFileList);
- }
- if (!Result)
- {
- Abort();
- }
- }
- if ((Mode == smBoth) || (Mode == smLocal))
- {
- Data.ModifiedRemoteFileList->AddStrings(Data.NewRemoteFileList);
- if (Data.ModifiedRemoteFileList->Count > 0)
- {
- if (!CopyToLocal(Data.ModifiedRemoteFileList, LocalDirectory,
- CopyParam, CopyParams))
- {
- Abort();
- }
- }
- }
- if ((Mode == smRemote) && Delete && (Data.NewRemoteFileList->Count > 0))
- {
- if (!DeleteFiles(Data.NewRemoteFileList))
- {
- Abort();
- }
- }
- }
- }
- __finally
- {
- if (Data.LocalFileList != NULL)
- {
- for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
- {
- delete reinterpret_cast<TSynchronizeFileData*>
- (Data.LocalFileList->Objects[Index]);
- }
- delete Data.LocalFileList;
- }
- TStringList * FileList = Data.NewRemoteFileList;
- while (FileList != Data.ModifiedRemoteFileList)
- {
- if (FileList != NULL)
- {
- for (int Index = 0; Index < FileList->Count; Index++)
- {
- delete static_cast<TRemoteFile*>(FileList->Objects[Index]);
- }
- delete FileList;
- }
- FileList = Data.ModifiedRemoteFileList;
- }
- delete LocalFileList;
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminal::SynchronizeFile(const AnsiString FileName,
- const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
- {
- TSynchronizeData * Data = static_cast<TSynchronizeData *>(Param);
- bool Modified = false;
- int Index = Data->LocalFileList->IndexOf(File->FileName);
- bool New = (Index < 0);
- if (!New)
- {
- TSynchronizeFileData * LocalData =
- reinterpret_cast<TSynchronizeFileData *>(Data->LocalFileList->Objects[Index]);
- LocalData->New = false;
- bool LocalDirectory = (LocalData->Attr & faDirectory) != 0;
- if (File->IsDirectory != LocalDirectory)
- {
- LogEvent(FORMAT("%s is directory on one side, but file on the another",
- (File->FileName)));
- }
- else if (!File->IsDirectory)
- {
- FILETIME LocalLastWriteTime;
- SYSTEMTIME SystemLastWriteTime;
- FileTimeToLocalFileTime(&LocalData->LastWriteTime, &LocalLastWriteTime);
- FileTimeToSystemTime(&LocalLastWriteTime, &SystemLastWriteTime);
- TDateTime LocalTime = SystemTimeToDateTime(SystemLastWriteTime);
- TDateTime RemoteTime = File->Modification;
- UnifyDateTimePrecision(LocalTime, RemoteTime);
- if (LocalTime < RemoteTime)
- {
- Modified = true;
- }
- else if (LocalTime > RemoteTime)
- {
- LocalData->Modified = true;
- }
- }
- else
- {
- DoSynchronizeDirectory(
- Data->LocalDirectory + File->FileName,
- Data->RemoteDirectory + File->FileName,
- Data->Mode, Data->CopyParam, Data->Params, Data->OnSynchronizeDirectory);
- }
- }
- if (New || Modified)
- {
- assert(!New || !Modified);
- TStringList * FileList = New ? Data->NewRemoteFileList :
- Data->ModifiedRemoteFileList;
- FileList->AddObject(FileName,
- const_cast<TRemoteFile *>(File)->Duplicate());
- }
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::CopyToRemote(TStrings * FilesToCopy,
- const AnsiString TargetDir, const TCopyParamType * CopyParam, int Params)
- {
- assert(FFileSystem);
- assert(FilesToCopy);
- bool Result = false;
- bool DisconnectWhenComplete = false;
- try
- {
- __int64 Size;
- if (CopyParam->CalculateSize)
- {
- CalculateLocalFilesSize(FilesToCopy, Size);
- }
- TFileOperationProgressType OperationProgress(FOnProgress, FOnFinished);
- OperationProgress.Start((Params & cpDelete ? foMove : foCopy), osLocal,
- FilesToCopy->Count, Params & cpDragDrop, TargetDir);
- if (CopyParam->CalculateSize)
- {
- OperationProgress.SetTotalSize(Size);
- }
- FOperationProgress = &OperationProgress;
- try
- {
- AnsiString UnlockedTargetDir = TranslateLockedPath(TargetDir, false);
- BeginTransaction();
- try
- {
- if (IsLogging())
- {
- LogEvent(FORMAT("Copying %d files/directories to remote directory "
- "\"%s\"", (FilesToCopy->Count, TargetDir)));
- LogEvent(CopyParam->LogStr);
- }
- FFileSystem->CopyToRemote(FilesToCopy, UnlockedTargetDir,
- CopyParam, Params, &OperationProgress, DisconnectWhenComplete);
- }
- __finally
- {
- if (Active)
- {
- ReactOnCommand(fsCopyToRemote);
- EndTransaction();
- }
- }
- if (OperationProgress.Cancel == csContinue)
- {
- Result = true;
- }
- }
- __finally
- {
- OperationProgress.Stop();
- FOperationProgress = NULL;
- }
- }
- catch (Exception &E)
- {
- CommandError(&E, LoadStr(TOREMOTE_COPY_ERROR));
- DisconnectWhenComplete = false;
- }
- if (DisconnectWhenComplete) CloseOnCompletion();
- return Result;
- }
- //---------------------------------------------------------------------------
- bool __fastcall TTerminal::CopyToLocal(TStrings * FilesToCopy,
- const AnsiString TargetDir, const TCopyParamType * CopyParam, int Params)
- {
- assert(FFileSystem);
- // see scp.c: sink(), tolocal()
- bool Result = false;
- bool OwnsFileList = (FilesToCopy == NULL);
- bool DisconnectWhenComplete = false;
- try
- {
- if (OwnsFileList)
- {
- FilesToCopy = new TStringList();
- FilesToCopy->Assign(Files->SelectedFiles);
- }
- BeginTransaction();
- try
- {
- __int64 TotalSize;
- bool TotalSizeKnown = false;
- TFileOperationProgressType OperationProgress(FOnProgress, FOnFinished);
- if (CopyParam->CalculateSize)
- {
- ExceptionOnFail = true;
- try
- {
- CalculateFilesSize(FilesToCopy, TotalSize, csIgnoreErrors);
- TotalSizeKnown = true;
- }
- __finally
- {
- ExceptionOnFail = false;
- }
- }
- OperationProgress.Start((Params & cpDelete ? foMove : foCopy), osRemote,
- FilesToCopy->Count, Params & cpDragDrop, TargetDir);
- if (TotalSizeKnown)
- {
- OperationProgress.SetTotalSize(TotalSize);
- }
- FOperationProgress = &OperationProgress;
- try
- {
- try
- {
- try
- {
- FFileSystem->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params,
- &OperationProgress, DisconnectWhenComplete);
- }
- __finally
- {
- if (Active)
- {
- ReactOnCommand(fsCopyToLocal);
- }
- }
- }
- catch (Exception &E)
- {
- CommandError(&E, LoadStr(TOLOCAL_COPY_ERROR));
- DisconnectWhenComplete = false;
- }
- if (OperationProgress.Cancel == csContinue)
- {
- Result = true;
- }
- }
- __finally
- {
- FOperationProgress = NULL;
- OperationProgress.Stop();
- }
- }
- __finally
- {
- // If session is still active (no fatal error) we reload directory
- // by calling EndTransaction
- EndTransaction();
- }
- }
- __finally
- {
- if (OwnsFileList) delete FilesToCopy;
- }
- if (DisconnectWhenComplete) CloseOnCompletion();
- return Result;
- }
- //---------------------------------------------------------------------------
- __fastcall TTerminalList::TTerminalList(TConfiguration * AConfiguration) :
- TObjectList()
- {
- assert(AConfiguration);
- FConfiguration = AConfiguration;
- }
- //---------------------------------------------------------------------------
- __fastcall TTerminalList::~TTerminalList()
- {
- assert(Count == 0);
- }
- //---------------------------------------------------------------------------
- TTerminal * __fastcall TTerminalList::NewTerminal(TSessionData * Data)
- {
- TTerminal * Terminal = new TTerminal();
- try
- {
- Terminal->Configuration = FConfiguration;
- Terminal->SessionData = Data;
- Add(Terminal);
- }
- catch(...)
- {
- delete Terminal;
- throw;
- }
- return Terminal;
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminalList::FreeTerminal(TTerminal * Terminal)
- {
- assert(IndexOf(Terminal) >= 0);
- Remove(Terminal);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminalList::FreeAndNullTerminal(TTerminal * & Terminal)
- {
- TTerminal * T = Terminal;
- Terminal = NULL;
- FreeTerminal(T);
- }
- //---------------------------------------------------------------------------
- TTerminal * __fastcall TTerminalList::GetTerminal(int Index)
- {
- return dynamic_cast<TTerminal *>(Items[Index]);
- }
- //---------------------------------------------------------------------------
- void __fastcall TTerminalList::Idle()
- {
- TTerminal * Terminal;
- for (int i = 0; i < Count; i++)
- {
- Terminal = Terminals[i];
- if (Terminal->Status == sshReady)
- {
- Terminal->Idle();
- }
- }
- }
|