Terminal.cpp 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "Terminal.h"
  5. #include <SysUtils.hpp>
  6. #include <FileCtrl.hpp>
  7. #include "Common.h"
  8. #include "FileBuffer.h"
  9. #include "FileSystems.h"
  10. #include "Interface.h"
  11. #include "RemoteFiles.h"
  12. #include "ScpFileSystem.h"
  13. #include "SftpFileSystem.h"
  14. #include "TextsCore.h"
  15. //---------------------------------------------------------------------------
  16. #pragma package(smart_init)
  17. //---------------------------------------------------------------------------
  18. #define COMMAND_ERROR_ARI(MESSAGE, REPEAT) \
  19. { \
  20. int Result = CommandError(&E, MESSAGE, qaRetry | qaSkip | qaAbort); \
  21. switch (Result) { \
  22. case qaRetry: { REPEAT; } break; \
  23. case qaAbort: Abort(); \
  24. } \
  25. }
  26. #define FILE_OPERATION_LOOP_EX(ALLOW_SKIP, MESSAGE, OPERATION) \
  27. FILE_OPERATION_LOOP_CUSTOM(this, ALLOW_SKIP, MESSAGE, OPERATION)
  28. //---------------------------------------------------------------------------
  29. struct TMoveFileParams
  30. {
  31. AnsiString Target;
  32. AnsiString FileMask;
  33. };
  34. //---------------------------------------------------------------------------
  35. __fastcall TTerminal::TTerminal(): TSecureShell()
  36. {
  37. FFiles = new TRemoteDirectory(this);
  38. FExceptionOnFail = 0;
  39. FInTransaction = 0;
  40. FReadCurrentDirectoryPending = false;
  41. FReadDirectoryPending = false;
  42. FUsersGroupsLookedup = False;
  43. FGroups = new TUsersGroupsList();
  44. FUsers = new TUsersGroupsList();
  45. FOnProgress = NULL;
  46. FOnFinished = NULL;
  47. FOnDeleteLocalFile = NULL;
  48. FAdditionalInfo = NULL;
  49. FUseBusyCursor = True;
  50. FLockDirectory = "";
  51. FDirectoryCache = new TRemoteDirectoryCache();
  52. FDirectoryChangesCache = NULL;
  53. FFSProtocol = cfsUnknown;
  54. }
  55. //---------------------------------------------------------------------------
  56. __fastcall TTerminal::~TTerminal()
  57. {
  58. if (SessionData->CacheDirectoryChanges && SessionData->PreserveDirectoryChanges &&
  59. (FDirectoryChangesCache != NULL))
  60. {
  61. Configuration->SaveDirectoryChangesCache(SessionData->SessionKey,
  62. FDirectoryChangesCache);
  63. }
  64. SAFE_DESTROY(FFileSystem);
  65. delete FFiles;
  66. delete FGroups;
  67. delete FUsers;
  68. delete FDirectoryCache;
  69. delete FDirectoryChangesCache;
  70. delete FAdditionalInfo;
  71. }
  72. //---------------------------------------------------------------------------
  73. void __fastcall TTerminal::KeepAlive()
  74. {
  75. if (SessionData->PingType == ptDummyCommand)
  76. {
  77. LogEvent("Executing dummy command to keep session alive.");
  78. assert(Active);
  79. assert(FFileSystem != NULL);
  80. try
  81. {
  82. FFileSystem->KeepAlive();
  83. }
  84. catch(Exception & E)
  85. {
  86. if (Active)
  87. {
  88. DoHandleExtendedException(&E);
  89. }
  90. else
  91. {
  92. throw;
  93. }
  94. }
  95. }
  96. else
  97. {
  98. TSecureShell::KeepAlive();
  99. }
  100. }
  101. //---------------------------------------------------------------------------
  102. bool __fastcall TTerminal::IsAbsolutePath(const AnsiString Path)
  103. {
  104. return !Path.IsEmpty() && Path[1] == '/';
  105. }
  106. //---------------------------------------------------------------------------
  107. AnsiString __fastcall TTerminal::ExpandFileName(AnsiString Path,
  108. const AnsiString BasePath)
  109. {
  110. Path = UnixExcludeTrailingBackslash(Path);
  111. if (!IsAbsolutePath(Path) && !BasePath.IsEmpty())
  112. {
  113. // TODO: Handle more complicated cases like "../../xxx"
  114. if (Path == "..")
  115. {
  116. Path = UnixExcludeTrailingBackslash(UnixExtractFilePath(
  117. UnixExcludeTrailingBackslash(BasePath)));
  118. }
  119. else
  120. {
  121. Path = UnixIncludeTrailingBackslash(BasePath) + Path;
  122. }
  123. }
  124. return Path;
  125. }
  126. //---------------------------------------------------------------------------
  127. AnsiString __fastcall TTerminal::GetProtocolName()
  128. {
  129. assert(FFileSystem);
  130. return FFileSystem->ProtocolName;
  131. }
  132. //---------------------------------------------------------------------------
  133. void __fastcall TTerminal::Close()
  134. {
  135. // file system cannot be destoryed here, moved to destructor
  136. TSecureShell::Close();
  137. }
  138. //---------------------------------------------------------------------------
  139. void __fastcall TTerminal::Open()
  140. {
  141. TSecureShell::Open();
  142. assert(!FFileSystem);
  143. if ((SessionData->FSProtocol == fsSCPonly) ||
  144. (SessionData->FSProtocol == fsSFTP && SshFallbackCmd()))
  145. {
  146. FFSProtocol = cfsSCP;
  147. FFileSystem = new TSCPFileSystem(this);
  148. LogEvent("Using SCP protocol.");
  149. }
  150. else
  151. {
  152. FFSProtocol = cfsSFTP;
  153. FFileSystem = new TSFTPFileSystem(this);
  154. LogEvent("Using SFTP protocol.");
  155. }
  156. if (SessionData->CacheDirectoryChanges)
  157. {
  158. FDirectoryChangesCache = new TRemoteDirectoryChangesCache();
  159. if (SessionData->PreserveDirectoryChanges)
  160. {
  161. Configuration->LoadDirectoryChangesCache(SessionData->SessionKey,
  162. FDirectoryChangesCache);
  163. }
  164. }
  165. }
  166. //---------------------------------------------------------------------------
  167. bool __fastcall TTerminal::GetIsCapable(TFSCapability Capability) const
  168. {
  169. assert(FFileSystem);
  170. return FFileSystem->IsCapable(Capability);
  171. }
  172. //---------------------------------------------------------------------------
  173. TStrings * __fastcall TTerminal::GetAdditionalInfo()
  174. {
  175. bool Initial = (FAdditionalInfo == NULL);
  176. if (Initial)
  177. {
  178. FAdditionalInfo = new TStringList();
  179. }
  180. assert(FFileSystem);
  181. FFileSystem->AdditionalInfo(FAdditionalInfo, Initial);
  182. return FAdditionalInfo;
  183. }
  184. //---------------------------------------------------------------------------
  185. AnsiString __fastcall TTerminal::AbsolutePath(AnsiString Path)
  186. {
  187. return FFileSystem->AbsolutePath(Path);
  188. }
  189. //---------------------------------------------------------------------------
  190. void __fastcall TTerminal::ReactOnCommand(int /*TFSCommand*/ Cmd)
  191. {
  192. bool ChangesDirectory = false;
  193. bool ModifiesFiles = false;
  194. switch ((TFSCommand)Cmd) {
  195. case fsChangeDirectory:
  196. case fsHomeDirectory:
  197. ChangesDirectory = true;
  198. break;
  199. case fsCopyToRemote:
  200. case fsDeleteFile:
  201. case fsRenameFile:
  202. case fsMoveFile:
  203. case fsCreateDirectory:
  204. case fsChangeMode:
  205. case fsChangeGroup:
  206. case fsChangeOwner:
  207. case fsChangeProperties:
  208. case fsAnyCommand:
  209. ModifiesFiles = true;
  210. break;
  211. }
  212. if (ChangesDirectory)
  213. {
  214. if (!FInTransaction)
  215. {
  216. ReadCurrentDirectory();
  217. ReadDirectory(false);
  218. }
  219. else
  220. {
  221. FReadCurrentDirectoryPending = true;
  222. FReadDirectoryPending = true;
  223. }
  224. }
  225. else
  226. if (ModifiesFiles)
  227. {
  228. if (!FInTransaction) ReadDirectory(true);
  229. else FReadDirectoryPending = true;
  230. }
  231. }
  232. //---------------------------------------------------------------------------
  233. void __fastcall TTerminal::TerminalError(AnsiString Msg)
  234. {
  235. TerminalError(NULL, Msg);
  236. }
  237. //---------------------------------------------------------------------------
  238. void __fastcall TTerminal::TerminalError(Exception * E, AnsiString Msg)
  239. {
  240. throw ETerminal(E, Msg);
  241. }
  242. //---------------------------------------------------------------------------
  243. int __fastcall TTerminal::FileOperationLoop(TFileOperationEvent CallBackFunc,
  244. TFileOperationProgressType * OperationProgress, bool AllowSkip,
  245. const AnsiString Message, void * Param1, void * Param2)
  246. {
  247. assert(CallBackFunc);
  248. int Result;
  249. FILE_OPERATION_LOOP_EX
  250. (
  251. AllowSkip, Message,
  252. Result = CallBackFunc(Param1, Param2);
  253. );
  254. return Result;
  255. }
  256. //---------------------------------------------------------------------------
  257. AnsiString __fastcall TTerminal::TranslateLockedPath(AnsiString Path, bool Lock)
  258. {
  259. if (!SessionData->LockInHome || Path.IsEmpty() || (Path[1] != '/'))
  260. return Path;
  261. if (Lock)
  262. {
  263. if (Path.SubString(1, FLockDirectory.Length()) == FLockDirectory)
  264. {
  265. Path.Delete(1, FLockDirectory.Length());
  266. if (Path.IsEmpty()) Path = "/";
  267. }
  268. }
  269. else
  270. {
  271. Path = UnixExcludeTrailingBackslash(FLockDirectory + Path);
  272. }
  273. return Path;
  274. }
  275. //---------------------------------------------------------------------------
  276. void __fastcall TTerminal::ClearCaches()
  277. {
  278. FDirectoryCache->Clear();
  279. if (FDirectoryChangesCache != NULL)
  280. {
  281. FDirectoryChangesCache->Clear();
  282. }
  283. }
  284. //---------------------------------------------------------------------------
  285. void __fastcall TTerminal::ClearCachedFileList(const AnsiString Path,
  286. bool SubDirs)
  287. {
  288. FDirectoryCache->ClearFileList(Path, SubDirs);
  289. }
  290. //---------------------------------------------------------------------------
  291. void __fastcall TTerminal::AddCachedFileList(TRemoteFileList * FileList)
  292. {
  293. FDirectoryCache->AddFileList(FileList);
  294. }
  295. //---------------------------------------------------------------------------
  296. void __fastcall TTerminal::SetCurrentDirectory(AnsiString value)
  297. {
  298. assert(FFileSystem);
  299. value = TranslateLockedPath(value, false);
  300. if (value != FFileSystem->CurrentDirectory)
  301. {
  302. ChangeDirectory(value);
  303. }
  304. }
  305. //---------------------------------------------------------------------------
  306. AnsiString __fastcall TTerminal::GetCurrentDirectory()
  307. {
  308. if (FFileSystem)
  309. {
  310. FCurrentDirectory = FFileSystem->CurrentDirectory;
  311. if (FCurrentDirectory.IsEmpty())
  312. {
  313. ReadCurrentDirectory();
  314. }
  315. }
  316. return TranslateLockedPath(FCurrentDirectory, true);
  317. }
  318. //---------------------------------------------------------------------------
  319. AnsiString __fastcall TTerminal::PeekCurrentDirectory()
  320. {
  321. if (FFileSystem)
  322. {
  323. FCurrentDirectory = FFileSystem->CurrentDirectory;
  324. }
  325. return TranslateLockedPath(FCurrentDirectory, true);
  326. }
  327. //---------------------------------------------------------------------------
  328. TUsersGroupsList * __fastcall TTerminal::GetGroups()
  329. {
  330. assert(FFileSystem);
  331. if (!FUsersGroupsLookedup && SessionData->LookupUserGroups &&
  332. IsCapable[fcUserGroupListing])
  333. {
  334. LookupUsersGroups();
  335. }
  336. return FGroups;
  337. }
  338. //---------------------------------------------------------------------------
  339. TUsersGroupsList * __fastcall TTerminal::GetUsers()
  340. {
  341. assert(FFileSystem);
  342. if (!FUsersGroupsLookedup && SessionData->LookupUserGroups &&
  343. IsCapable[fcUserGroupListing])
  344. {
  345. LookupUsersGroups();
  346. }
  347. return FUsers;
  348. }
  349. //---------------------------------------------------------------------------
  350. AnsiString __fastcall TTerminal::GetUserName() const
  351. {
  352. // in future might be implemented to detect username similar to GetUserGroups
  353. return SessionData->UserName;
  354. }
  355. //---------------------------------------------------------------------------
  356. bool __fastcall TTerminal::GetAreCachesEmpty() const
  357. {
  358. return FDirectoryCache->IsEmpty &&
  359. ((FDirectoryChangesCache == NULL) || FDirectoryChangesCache->IsEmpty);
  360. }
  361. //---------------------------------------------------------------------------
  362. void __fastcall TTerminal::DoChangeDirectory()
  363. {
  364. if (FOnChangeDirectory)
  365. {
  366. FOnChangeDirectory(this);
  367. }
  368. }
  369. //---------------------------------------------------------------------------
  370. void __fastcall TTerminal::DoReadDirectory(bool ReloadOnly)
  371. {
  372. if (FOnReadDirectory)
  373. {
  374. FOnReadDirectory(this, ReloadOnly);
  375. }
  376. }
  377. //---------------------------------------------------------------------------
  378. void __fastcall TTerminal::DoStartReadDirectory()
  379. {
  380. if (FOnStartReadDirectory)
  381. {
  382. FOnStartReadDirectory(this);
  383. }
  384. }
  385. //---------------------------------------------------------------------------
  386. void __fastcall TTerminal::BeginTransaction()
  387. {
  388. if (!FInTransaction)
  389. {
  390. FReadCurrentDirectoryPending = false;
  391. FReadDirectoryPending = false;
  392. }
  393. FInTransaction++;
  394. }
  395. //---------------------------------------------------------------------------
  396. void __fastcall TTerminal::EndTransaction()
  397. {
  398. // it connection was closed due to fatal error during transaction, do nothing
  399. if (Active)
  400. {
  401. if (!FInTransaction)
  402. TerminalError("Can't end transaction, not in transaction");
  403. assert(FInTransaction > 0);
  404. FInTransaction--;
  405. if (FInTransaction == 0)
  406. {
  407. try
  408. {
  409. if (FReadCurrentDirectoryPending) ReadCurrentDirectory();
  410. if (FReadDirectoryPending) ReadDirectory(!FReadCurrentDirectoryPending);
  411. }
  412. __finally
  413. {
  414. FReadCurrentDirectoryPending = false;
  415. FReadDirectoryPending = false;
  416. }
  417. }
  418. }
  419. }
  420. //---------------------------------------------------------------------------
  421. void __fastcall TTerminal::SetExceptionOnFail(bool value)
  422. {
  423. if (value) FExceptionOnFail++;
  424. else
  425. {
  426. if (FExceptionOnFail == 0)
  427. throw Exception("ExceptionOnFail is already zero.");
  428. FExceptionOnFail--;
  429. }
  430. }
  431. //---------------------------------------------------------------------------
  432. bool __fastcall TTerminal::GetExceptionOnFail() const
  433. {
  434. return (bool)(FExceptionOnFail > 0);
  435. }
  436. //---------------------------------------------------------------------------
  437. void __fastcall TTerminal::CommandError(Exception * E, const AnsiString Msg)
  438. {
  439. CommandError(E, Msg, 0);
  440. }
  441. //---------------------------------------------------------------------------
  442. int __fastcall TTerminal::CommandError(Exception * E, const AnsiString Msg,
  443. int Answers)
  444. {
  445. int Result = 0;
  446. if (E && E->InheritsFrom(__classid(EFatal)))
  447. {
  448. FatalError(E, Msg);
  449. }
  450. else if (E && E->InheritsFrom(__classid(EAbort)))
  451. {
  452. // resent EAbort exception
  453. Abort();
  454. }
  455. else if (ExceptionOnFail)
  456. {
  457. throw ECommand(E, Msg);
  458. }
  459. else if (!Answers)
  460. {
  461. ECommand * ECmd = new ECommand(E, Msg);
  462. try
  463. {
  464. DoShowExtendedException(ECmd);
  465. }
  466. __finally
  467. {
  468. delete ECmd;
  469. }
  470. }
  471. else
  472. {
  473. Result = DoQueryUser(Msg, E, Answers, qpAllowContinueOnError);
  474. }
  475. return Result;
  476. }
  477. //---------------------------------------------------------------------------
  478. bool __fastcall TTerminal::HandleException(Exception * E)
  479. {
  480. if (ExceptionOnFail)
  481. {
  482. return false;
  483. }
  484. else
  485. {
  486. DoHandleExtendedException(E);
  487. return true;
  488. }
  489. }
  490. //---------------------------------------------------------------------------
  491. void __fastcall TTerminal::CloseOnCompletion(const AnsiString Message)
  492. {
  493. LogEvent("Closing session after completed operation (as requested by user)");
  494. Close();
  495. throw ESshTerminate(NULL,
  496. Message.IsEmpty() ? LoadStr(CLOSED_ON_COMPLETION) : Message);
  497. }
  498. //---------------------------------------------------------------------------
  499. int __fastcall TTerminal::ConfirmFileOverwrite(const AnsiString FileName,
  500. const TOverwriteFileParams * FileParams, int Answers, int Params,
  501. TOperationSide Side)
  502. {
  503. AnsiString Message = FMTLOAD((Side == osLocal ? LOCAL_FILE_OVERWRITE :
  504. REMOTE_FILE_OVERWRITE), (FileName));
  505. if (FileParams)
  506. {
  507. Message = FMTLOAD(FILE_OVERWRITE_DETAILS, (Message,
  508. IntToStr(FileParams->SourceSize),
  509. FormatDateTime("ddddd tt", FileParams->SourceTimestamp),
  510. IntToStr(FileParams->DestSize),
  511. FormatDateTime("ddddd tt", FileParams->DestTimestamp)));
  512. }
  513. return DoQueryUser(Message, Answers, Params);
  514. }
  515. //---------------------------------------------------------------------------
  516. void __fastcall TTerminal::FileModified(const TRemoteFile * File,
  517. const AnsiString FileName)
  518. {
  519. if (SessionData->CacheDirectories)
  520. {
  521. if ((File != NULL) && (File->Directory != NULL))
  522. {
  523. if (File->IsDirectory)
  524. {
  525. // do not use UnixIncludeTrailingBackslash(CurrentDirectory)
  526. DirectoryModified(
  527. File->Directory->FullDirectory + File->FileName, true);
  528. }
  529. DirectoryModified(File->Directory->Directory, false);
  530. }
  531. else if (!FileName.IsEmpty())
  532. {
  533. AnsiString Directory = UnixExtractFilePath(FileName);
  534. DirectoryModified(
  535. !Directory.IsEmpty() ? Directory : CurrentDirectory, false);
  536. }
  537. }
  538. }
  539. //---------------------------------------------------------------------------
  540. void __fastcall TTerminal::DoDirectoryModified(const AnsiString Path, bool SubDirs)
  541. {
  542. if (OnDirectoryModified != NULL)
  543. {
  544. OnDirectoryModified(this, Path, SubDirs);
  545. }
  546. }
  547. //---------------------------------------------------------------------------
  548. void __fastcall TTerminal::DirectoryModified(const AnsiString Path, bool SubDirs)
  549. {
  550. ClearCachedFileList(Path, SubDirs);
  551. DoDirectoryModified(Path, SubDirs);
  552. }
  553. //---------------------------------------------------------------------------
  554. void __fastcall TTerminal::DirectoryLoaded(TRemoteFileList * FileList)
  555. {
  556. AddCachedFileList(FileList);
  557. }
  558. //---------------------------------------------------------------------------
  559. void __fastcall TTerminal::ReloadDirectory()
  560. {
  561. if (SessionData->CacheDirectories)
  562. {
  563. DirectoryModified(CurrentDirectory, false);
  564. }
  565. if (SessionData->CacheDirectoryChanges)
  566. {
  567. assert(FDirectoryChangesCache != NULL);
  568. FDirectoryChangesCache->ClearDirectoryChange(CurrentDirectory);
  569. }
  570. ReadCurrentDirectory();
  571. FReadCurrentDirectoryPending = false;
  572. ReadDirectory(true);
  573. FReadDirectoryPending = false;
  574. }
  575. //---------------------------------------------------------------------------
  576. void __fastcall TTerminal::RefreshDirectory()
  577. {
  578. if (SessionData->CacheDirectories &&
  579. FDirectoryCache->HasNewerFileList(CurrentDirectory, FFiles->Timestamp))
  580. {
  581. // Second parameter was added to allow (rather force) using the cache.
  582. // Before, the directory was reloaded always, it seems useless,
  583. // has it any reason?
  584. ReadDirectory(true, true);
  585. FReadDirectoryPending = false;
  586. }
  587. }
  588. //---------------------------------------------------------------------------
  589. void __fastcall TTerminal::EnsureNonExistence(const AnsiString FileName)
  590. {
  591. // if filename doesn't contain path, we check for existence of file
  592. if ((UnixExtractFileDir(FileName).IsEmpty()) &&
  593. UnixComparePaths(CurrentDirectory, FFiles->Directory))
  594. {
  595. TRemoteFile *File = FFiles->FindFile(FileName);
  596. if (File)
  597. {
  598. if (File->IsDirectory) throw ECommand(NULL, FMTLOAD(RENAME_CREATE_DIR_EXISTS, (FileName)));
  599. else throw ECommand(NULL, FMTLOAD(RENAME_CREATE_FILE_EXISTS, (FileName)));
  600. }
  601. }
  602. }
  603. //---------------------------------------------------------------------------
  604. void __fastcall TTerminal::DoStartup()
  605. {
  606. LogEvent("Doing startup conversation with host.");
  607. BeginTransaction();
  608. try
  609. {
  610. UpdateStatus(sshStartup);
  611. // Make sure that directory would be loaded at last
  612. FReadCurrentDirectoryPending = true;
  613. FReadDirectoryPending = true;
  614. FFileSystem->DoStartup();
  615. if (SessionData->LookupUserGroups && IsCapable[fcUserGroupListing])
  616. {
  617. LookupUsersGroups();
  618. }
  619. UpdateStatus(sshOpenDirectory);
  620. if (!SessionData->RemoteDirectory.IsEmpty())
  621. {
  622. ChangeDirectory(SessionData->RemoteDirectory);
  623. }
  624. }
  625. __finally
  626. {
  627. EndTransaction();
  628. }
  629. LogEvent("Startup conversation with host finished.");
  630. UpdateStatus(sshReady);
  631. }
  632. //---------------------------------------------------------------------------
  633. void __fastcall TTerminal::ReadCurrentDirectory()
  634. {
  635. assert(FFileSystem);
  636. try
  637. {
  638. LogEvent("Getting current directory name.");
  639. AnsiString OldDirectory = FFileSystem->CurrentDirectory;
  640. FFileSystem->ReadCurrentDirectory();
  641. ReactOnCommand(fsCurrentDirectory);
  642. if (SessionData->CacheDirectoryChanges)
  643. {
  644. assert(FDirectoryChangesCache != NULL);
  645. FDirectoryChangesCache->AddDirectoryChange(OldDirectory,
  646. FLastDirectoryChange, CurrentDirectory);
  647. }
  648. if (OldDirectory.IsEmpty())
  649. {
  650. FLockDirectory = (SessionData->LockInHome ?
  651. FFileSystem->CurrentDirectory : AnsiString(""));
  652. }
  653. if (OldDirectory != FFileSystem->CurrentDirectory) DoChangeDirectory();
  654. }
  655. catch (Exception &E)
  656. {
  657. CommandError(&E, LoadStr(READ_CURRENT_DIR_ERROR));
  658. }
  659. }
  660. //---------------------------------------------------------------------------
  661. void __fastcall TTerminal::ReadDirectory(bool ReloadOnly, bool ForceCache)
  662. {
  663. bool LoadedFromCache = false;
  664. if (SessionData->CacheDirectories && FDirectoryCache->HasFileList(CurrentDirectory))
  665. {
  666. if (ReloadOnly && !ForceCache)
  667. {
  668. LogEvent("Cached directory not reloaded.");
  669. }
  670. else
  671. {
  672. DoStartReadDirectory();
  673. try
  674. {
  675. LoadedFromCache = FDirectoryCache->GetFileList(CurrentDirectory, FFiles);
  676. }
  677. __finally
  678. {
  679. DoReadDirectory(ReloadOnly);
  680. }
  681. if (LoadedFromCache)
  682. {
  683. LogEvent("Directory content loaded from cache.");
  684. }
  685. else
  686. {
  687. LogEvent("Cached Directory content has been removed.");
  688. }
  689. }
  690. }
  691. if (!LoadedFromCache)
  692. {
  693. DoStartReadDirectory();
  694. FFiles->Directory = CurrentDirectory;
  695. try
  696. {
  697. try
  698. {
  699. CustomReadDirectory(FFiles);
  700. }
  701. __finally
  702. {
  703. // this must be called before error is displayed, otherwise
  704. // TUnixDirView would be drawn with invalid data (it keeps reference
  705. // to already destoroyed old listing)
  706. DoReadDirectory(ReloadOnly);
  707. if (Active)
  708. {
  709. if (SessionData->CacheDirectories)
  710. {
  711. DirectoryLoaded(FFiles);
  712. }
  713. }
  714. }
  715. }
  716. catch (Exception &E)
  717. {
  718. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FFiles->Directory))));
  719. }
  720. }
  721. }
  722. //---------------------------------------------------------------------------
  723. void __fastcall TTerminal::CustomReadDirectory(TRemoteFileList * FileList)
  724. {
  725. assert(FileList);
  726. assert(FFileSystem);
  727. FFileSystem->ReadDirectory(FileList);
  728. ReactOnCommand(fsListDirectory);
  729. }
  730. //---------------------------------------------------------------------------
  731. TRemoteFileList * TTerminal::ReadDirectoryListing(AnsiString Directory)
  732. {
  733. TRemoteFileList * FileList;
  734. try
  735. {
  736. FileList = new TRemoteFileList();
  737. try
  738. {
  739. FileList->Directory = Directory;
  740. AnsiString Directory = UnixIncludeTrailingBackslash(Directory);
  741. ExceptionOnFail = true;
  742. try
  743. {
  744. ReadDirectory(FileList);
  745. }
  746. __finally
  747. {
  748. ExceptionOnFail = false;
  749. }
  750. }
  751. catch(...)
  752. {
  753. delete FileList;
  754. FileList = NULL;
  755. throw;
  756. }
  757. }
  758. catch(Exception & E)
  759. {
  760. COMMAND_ERROR_ARI
  761. (
  762. "",
  763. FileList = ReadDirectoryListing(Directory);
  764. );
  765. }
  766. return FileList;
  767. }
  768. //---------------------------------------------------------------------------
  769. void __fastcall TTerminal::ProcessDirectory(const AnsiString DirName,
  770. TProcessFileEvent CallBackFunc, void * Param)
  771. {
  772. TRemoteFileList * FileList = ReadDirectoryListing(DirName);
  773. // skip if directory listing fails and user selects "skip"
  774. if (FileList)
  775. {
  776. try
  777. {
  778. AnsiString Directory = UnixIncludeTrailingBackslash(DirName);
  779. TRemoteFile * File;
  780. for (int Index = 0; Index < FileList->Count; Index++)
  781. {
  782. File = FileList->Files[Index];
  783. if (!File->IsParentDirectory && !File->IsThisDirectory)
  784. {
  785. CallBackFunc(Directory + File->FileName, File, Param);
  786. }
  787. }
  788. }
  789. __finally
  790. {
  791. delete FileList;
  792. }
  793. }
  794. }
  795. //---------------------------------------------------------------------------
  796. void __fastcall TTerminal::ReadDirectory(TRemoteFileList * FileList)
  797. {
  798. try
  799. {
  800. CustomReadDirectory(FileList);
  801. }
  802. catch (Exception &E)
  803. {
  804. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FileList->Directory))));
  805. }
  806. }
  807. //---------------------------------------------------------------------------
  808. void __fastcall TTerminal::ReadSymlink(TRemoteFile * SymlinkFile,
  809. TRemoteFile *& File)
  810. {
  811. assert(FFileSystem);
  812. try
  813. {
  814. LogEvent(FORMAT("Reading symlink \"%s\".", (SymlinkFile->FileName)));
  815. FFileSystem->ReadSymlink(SymlinkFile, File);
  816. ReactOnCommand(fsReadSymlink);
  817. }
  818. catch (Exception &E)
  819. {
  820. CommandError(&E, FMTLOAD(READ_SYMLINK_ERROR, (SymlinkFile->FileName)));
  821. }
  822. }
  823. //---------------------------------------------------------------------------
  824. void __fastcall TTerminal::ReadFile(const AnsiString FileName,
  825. TRemoteFile *& File)
  826. {
  827. assert(FFileSystem);
  828. File = NULL;
  829. try
  830. {
  831. LogEvent(FORMAT("Listing file \"%s\".", (FileName)));
  832. FFileSystem->ReadFile(FileName, File);
  833. ReactOnCommand(fsListFile);
  834. }
  835. catch (Exception &E)
  836. {
  837. if (File) delete File;
  838. File = NULL;
  839. CommandError(&E, FMTLOAD(LIST_DIR_ERROR, (FileName)));
  840. }
  841. }
  842. //---------------------------------------------------------------------------
  843. bool __fastcall TTerminal::ProcessFiles(TStrings * FileList,
  844. TFileOperation Operation, TProcessFileEvent ProcessFile, void * Param,
  845. TOperationSide Side)
  846. {
  847. assert(FFileSystem);
  848. assert(FileList);
  849. bool Result = false;
  850. bool DisconnectWhenComplete = false;
  851. try
  852. {
  853. TFileOperationProgressType Progress(FOnProgress, FOnFinished);
  854. Progress.Start(Operation, Side, FileList->Count);
  855. FOperationProgress = &Progress;
  856. try
  857. {
  858. BeginTransaction();
  859. try
  860. {
  861. int Index = 0;
  862. AnsiString FileName;
  863. bool Success;
  864. while ((Index < FileList->Count) && (Progress.Cancel == csContinue))
  865. {
  866. FileName = FileList->Strings[Index];
  867. try
  868. {
  869. Success = false;
  870. ProcessFile(FileName, (TRemoteFile *)FileList->Objects[Index], Param);
  871. Success = true;
  872. }
  873. __finally
  874. {
  875. Progress.Finish(FileName, Success, DisconnectWhenComplete);
  876. }
  877. Index++;
  878. }
  879. }
  880. __finally
  881. {
  882. EndTransaction();
  883. }
  884. if (Progress.Cancel == csContinue)
  885. {
  886. Result = true;
  887. }
  888. }
  889. __finally
  890. {
  891. FOperationProgress = NULL;
  892. Progress.Stop();
  893. }
  894. }
  895. catch (...)
  896. {
  897. DisconnectWhenComplete = false;
  898. // this was missing here. was it by purpose?
  899. // without it any error message is lost
  900. throw;
  901. }
  902. if (DisconnectWhenComplete)
  903. {
  904. CloseOnCompletion();
  905. }
  906. return Result;
  907. }
  908. //---------------------------------------------------------------------------
  909. void __fastcall TTerminal::DeleteFile(AnsiString FileName,
  910. const TRemoteFile * File, void * Recursive)
  911. {
  912. if (FileName.IsEmpty() && File)
  913. {
  914. FileName = File->FileName;
  915. }
  916. if (OperationProgress && OperationProgress->Operation == foDelete)
  917. {
  918. if (OperationProgress->Cancel != csContinue) Abort();
  919. OperationProgress->SetFile(FileName);
  920. }
  921. LogEvent(FORMAT("Deleting file \"%s\".", (FileName)));
  922. if (File) FileModified(File, FileName);
  923. DoDeleteFile(FileName, File, Recursive);
  924. ReactOnCommand(fsDeleteFile);
  925. }
  926. //---------------------------------------------------------------------------
  927. void __fastcall TTerminal::DoDeleteFile(const AnsiString FileName,
  928. const TRemoteFile * File, void * Recursive)
  929. {
  930. try
  931. {
  932. assert(FFileSystem);
  933. // 'File' parameter: SFTPFileSystem needs to know if file is file or directory
  934. FFileSystem->DeleteFile(FileName, File,
  935. Recursive ? *((bool*)Recursive) : true);
  936. }
  937. catch(Exception & E)
  938. {
  939. COMMAND_ERROR_ARI
  940. (
  941. FMTLOAD(DELETE_FILE_ERROR, (FileName)),
  942. DoDeleteFile(FileName, File, Recursive)
  943. );
  944. }
  945. }
  946. //---------------------------------------------------------------------------
  947. bool __fastcall TTerminal::DeleteFiles(TStrings * FilesToDelete, bool * Recursive)
  948. {
  949. return ProcessFiles(FilesToDelete, foDelete, DeleteFile, Recursive);
  950. }
  951. //---------------------------------------------------------------------------
  952. void __fastcall TTerminal::DeleteLocalFile(AnsiString FileName,
  953. const TRemoteFile * /*File*/, void * /*Param*/)
  954. {
  955. if (OnDeleteLocalFile == NULL)
  956. {
  957. if (!RecursiveDeleteFile(FileName, false))
  958. {
  959. throw Exception(FMTLOAD(DELETE_FILE_ERROR, (FileName)));
  960. }
  961. }
  962. else
  963. {
  964. OnDeleteLocalFile(FileName);
  965. }
  966. }
  967. //---------------------------------------------------------------------------
  968. bool __fastcall TTerminal::DeleteLocalFiles(TStrings * FileList)
  969. {
  970. return ProcessFiles(FileList, foDelete, DeleteLocalFile, NULL, osLocal);
  971. }
  972. //---------------------------------------------------------------------------
  973. void __fastcall TTerminal::CustomCommandOnFile(AnsiString FileName,
  974. const TRemoteFile * File, void * AParams)
  975. {
  976. TCustomCommandParams * Params = ((TCustomCommandParams *)AParams);
  977. if (FileName.IsEmpty() && File)
  978. {
  979. FileName = File->FileName;
  980. }
  981. if (OperationProgress && OperationProgress->Operation == foCustomCommand)
  982. {
  983. if (OperationProgress->Cancel != csContinue) Abort();
  984. OperationProgress->SetFile(FileName);
  985. }
  986. LogEvent(FORMAT("Executing custom command \"%s\" (%d) on file \"%s\".",
  987. (Params->Command, Params->Params, FileName)));
  988. if (File) FileModified(File, FileName);
  989. DoCustomCommandOnFile(FileName, File, Params->Command, Params->Params);
  990. ReactOnCommand(fsAnyCommand);
  991. }
  992. //---------------------------------------------------------------------------
  993. void __fastcall TTerminal::DoCustomCommandOnFile(AnsiString FileName,
  994. const TRemoteFile * File, AnsiString Command, int Params)
  995. {
  996. try
  997. {
  998. assert(FFileSystem);
  999. FFileSystem->CustomCommandOnFile(FileName, File, Command, Params);
  1000. }
  1001. catch(Exception & E)
  1002. {
  1003. COMMAND_ERROR_ARI
  1004. (
  1005. FMTLOAD(CUSTOM_COMMAND_ERROR, (Command, FileName)),
  1006. DoCustomCommandOnFile(FileName, File, Command, Params)
  1007. );
  1008. }
  1009. }
  1010. //---------------------------------------------------------------------------
  1011. void __fastcall TTerminal::CustomCommandOnFiles(AnsiString Command,
  1012. int Params, TStrings * Files)
  1013. {
  1014. TCustomCommandParams AParams;
  1015. AParams.Command = Command;
  1016. AParams.Params = Params;
  1017. ProcessFiles(Files, foCustomCommand, CustomCommandOnFile, &AParams);
  1018. }
  1019. //---------------------------------------------------------------------------
  1020. void __fastcall TTerminal::ChangeFileProperties(AnsiString FileName,
  1021. const TRemoteFile * File, /*const TRemoteProperties*/ void * Properties)
  1022. {
  1023. TRemoteProperties * RProperties = (TRemoteProperties *)Properties;
  1024. assert(RProperties && !RProperties->Valid.Empty());
  1025. if (FileName.IsEmpty() && File)
  1026. {
  1027. FileName = File->FileName;
  1028. }
  1029. if (OperationProgress && OperationProgress->Operation == foSetProperties)
  1030. {
  1031. if (OperationProgress->Cancel != csContinue) Abort();
  1032. OperationProgress->SetFile(FileName);
  1033. }
  1034. if (IsLogging())
  1035. {
  1036. LogEvent(FORMAT("Changing properties of \"%s\" (%s)",
  1037. (FileName, BooleanToEngStr(RProperties->Recursive))));
  1038. if (RProperties->Valid.Contains(vpRights))
  1039. {
  1040. LogEvent(FORMAT(" - mode: \"%s\"", (RProperties->Rights.ModeStr)));
  1041. }
  1042. if (RProperties->Valid.Contains(vpGroup))
  1043. {
  1044. LogEvent(FORMAT(" - group: \"%s\"", (RProperties->Group)));
  1045. }
  1046. if (RProperties->Valid.Contains(vpOwner))
  1047. {
  1048. LogEvent(FORMAT(" - owner: \"%s\"", (RProperties->Owner)));
  1049. }
  1050. }
  1051. if (File) FileModified(File, FileName);
  1052. DoChangeFileProperties(FileName, File, RProperties);
  1053. ReactOnCommand(fsChangeProperties);
  1054. }
  1055. //---------------------------------------------------------------------------
  1056. void __fastcall TTerminal::DoChangeFileProperties(const AnsiString FileName,
  1057. const TRemoteFile * File, const TRemoteProperties * Properties)
  1058. {
  1059. try
  1060. {
  1061. assert(FFileSystem);
  1062. FFileSystem->ChangeFileProperties(FileName, File, Properties);
  1063. }
  1064. catch(Exception & E)
  1065. {
  1066. COMMAND_ERROR_ARI
  1067. (
  1068. FMTLOAD(CHANGE_PROPERTIES_ERROR, (FileName)),
  1069. DoChangeFileProperties(FileName, File, Properties)
  1070. );
  1071. }
  1072. }
  1073. //---------------------------------------------------------------------------
  1074. void __fastcall TTerminal::ChangeFilesProperties(TStrings * FileList,
  1075. const TRemoteProperties * Properties)
  1076. {
  1077. ProcessFiles(FileList, foSetProperties, ChangeFileProperties, (void *)Properties);
  1078. }
  1079. //---------------------------------------------------------------------------
  1080. void __fastcall TTerminal::CalculateFileSize(AnsiString FileName,
  1081. const TRemoteFile * File, /*TCalculateSizeParams*/ void * Param)
  1082. {
  1083. assert(Param);
  1084. assert(File);
  1085. if (FileName.IsEmpty() && File)
  1086. {
  1087. FileName = File->FileName;
  1088. }
  1089. if (File->IsDirectory && !File->IsSymLink)
  1090. {
  1091. LogEvent(FORMAT("Getting size of directory \"%s\"", (FileName)));
  1092. DoCalculateDirectorySize(FileName, File,
  1093. static_cast<TCalculateSizeParams*>(Param));
  1094. }
  1095. else
  1096. {
  1097. static_cast<TCalculateSizeParams*>(Param)->Size += File->Size;
  1098. }
  1099. if (OperationProgress && OperationProgress->Operation == foCalculateSize)
  1100. {
  1101. if (OperationProgress->Cancel != csContinue) Abort();
  1102. OperationProgress->SetFile(FileName);
  1103. }
  1104. }
  1105. //---------------------------------------------------------------------------
  1106. void __fastcall TTerminal::DoCalculateDirectorySize(const AnsiString FileName,
  1107. const TRemoteFile * File, TCalculateSizeParams * Params)
  1108. {
  1109. try
  1110. {
  1111. ProcessDirectory(FileName, CalculateFileSize, Params);
  1112. }
  1113. catch(Exception & E)
  1114. {
  1115. if (!Active || ((Params->Params & csIgnoreErrors) == 0))
  1116. {
  1117. COMMAND_ERROR_ARI
  1118. (
  1119. FMTLOAD(CALCULATE_SIZE_ERROR, (FileName)),
  1120. DoCalculateDirectorySize(FileName, File, Params)
  1121. );
  1122. }
  1123. }
  1124. }
  1125. //---------------------------------------------------------------------------
  1126. void __fastcall TTerminal::CalculateFilesSize(TStrings * FileList,
  1127. __int64 & Size, int Params)
  1128. {
  1129. TCalculateSizeParams Param;
  1130. Param.Size = 0;
  1131. Param.Params = Params;
  1132. ProcessFiles(FileList, foCalculateSize, CalculateFileSize, &Param);
  1133. Size = Param.Size;
  1134. }
  1135. //---------------------------------------------------------------------------
  1136. void __fastcall TTerminal::RenameFile(const AnsiString FileName,
  1137. const AnsiString NewName)
  1138. {
  1139. LogEvent(FORMAT("Renaming file \"%s\" to \"%s\".", (FileName, NewName)));
  1140. DoRenameFile(FileName, NewName, false);
  1141. ReactOnCommand(fsRenameFile);
  1142. }
  1143. //---------------------------------------------------------------------------
  1144. void __fastcall TTerminal::RenameFile(const TRemoteFile * File,
  1145. const AnsiString NewName, bool CheckExistence)
  1146. {
  1147. assert(File && File->Directory == FFiles);
  1148. bool Proceed = true;
  1149. // if filename doesn't contain path, we check for existence of file
  1150. if ((File->FileName != NewName) && CheckExistence &&
  1151. Configuration->ConfirmOverwriting &&
  1152. UnixComparePaths(CurrentDirectory, FFiles->Directory))
  1153. {
  1154. TRemoteFile * DuplicateFile = FFiles->FindFile(NewName);
  1155. if (DuplicateFile)
  1156. {
  1157. AnsiString QuestionFmt;
  1158. if (DuplicateFile->IsDirectory) QuestionFmt = LoadStr(DIRECTORY_OVERWRITE);
  1159. else QuestionFmt = LoadStr(FILE_OVERWRITE);
  1160. int Result;
  1161. Result = DoQueryUser(FORMAT(QuestionFmt, (NewName)),
  1162. qaYes | qaNo, qpNeverAskAgainCheck);
  1163. if (Result == qaNeverAskAgain)
  1164. {
  1165. Proceed = true;
  1166. Configuration->ConfirmOverwriting = false;
  1167. }
  1168. else
  1169. {
  1170. Proceed = (Result == qaYes);
  1171. }
  1172. }
  1173. }
  1174. if (Proceed)
  1175. {
  1176. FileModified(File, File->FileName);
  1177. RenameFile(File->FileName, NewName);
  1178. }
  1179. }
  1180. //---------------------------------------------------------------------------
  1181. void __fastcall TTerminal::DoRenameFile(const AnsiString FileName,
  1182. const AnsiString NewName, bool Move)
  1183. {
  1184. try
  1185. {
  1186. assert(FFileSystem);
  1187. FFileSystem->RenameFile(FileName, NewName);
  1188. }
  1189. catch(Exception & E)
  1190. {
  1191. COMMAND_ERROR_ARI
  1192. (
  1193. FMTLOAD(Move ? MOVE_FILE_ERROR : RENAME_FILE_ERROR, (FileName, NewName)),
  1194. DoRenameFile(FileName, NewName, Move)
  1195. );
  1196. }
  1197. }
  1198. //---------------------------------------------------------------------------
  1199. void __fastcall TTerminal::MoveFile(const AnsiString FileName,
  1200. const TRemoteFile * File, /*const TMoveFileParams*/ void * Param)
  1201. {
  1202. if (OperationProgress && (OperationProgress->Operation == foRemoteMove))
  1203. {
  1204. if (OperationProgress->Cancel != csContinue) Abort();
  1205. OperationProgress->SetFile(FileName);
  1206. }
  1207. assert(Param != NULL);
  1208. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  1209. AnsiString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  1210. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  1211. LogEvent(FORMAT("Moving file \"%s\" to \"%s\".", (FileName, NewName)));
  1212. FileModified(File, FileName);
  1213. DoRenameFile(FileName, NewName, true);
  1214. ReactOnCommand(fsMoveFile);
  1215. }
  1216. //---------------------------------------------------------------------------
  1217. bool __fastcall TTerminal::MoveFiles(TStrings * FileList, const AnsiString Target,
  1218. const AnsiString FileMask)
  1219. {
  1220. TMoveFileParams Params;
  1221. Params.Target = Target;
  1222. Params.FileMask = FileMask;
  1223. DirectoryModified(Target, true);
  1224. return ProcessFiles(FileList, foRemoteMove, MoveFile, &Params);
  1225. }
  1226. //---------------------------------------------------------------------------
  1227. void __fastcall TTerminal::CreateDirectory(const AnsiString DirName,
  1228. const TRemoteProperties * Properties)
  1229. {
  1230. assert(FFileSystem);
  1231. EnsureNonExistence(DirName);
  1232. FileModified(NULL, DirName);
  1233. LogEvent(FORMAT("Creating directory \"%s\".", (DirName)));
  1234. DoCreateDirectory(DirName, Properties);
  1235. ReactOnCommand(fsCreateDirectory);
  1236. }
  1237. //---------------------------------------------------------------------------
  1238. void __fastcall TTerminal::DoCreateDirectory(const AnsiString DirName,
  1239. const TRemoteProperties * Properties)
  1240. {
  1241. try
  1242. {
  1243. assert(FFileSystem);
  1244. FFileSystem->CreateDirectory(DirName, Properties);
  1245. }
  1246. catch(Exception & E)
  1247. {
  1248. COMMAND_ERROR_ARI
  1249. (
  1250. FMTLOAD(CREATE_DIR_ERROR, (DirName)),
  1251. DoCreateDirectory(DirName, Properties)
  1252. );
  1253. }
  1254. }
  1255. //---------------------------------------------------------------------------
  1256. void __fastcall TTerminal::CreateLink(const AnsiString FileName,
  1257. const AnsiString PointTo, bool Symbolic)
  1258. {
  1259. assert(FFileSystem);
  1260. EnsureNonExistence(FileName);
  1261. if (SessionData->CacheDirectories)
  1262. {
  1263. DirectoryModified(CurrentDirectory, false);
  1264. }
  1265. LogEvent(FORMAT("Creating link \"%s\" to \"%s\" (symbolic: %s).",
  1266. (FileName, PointTo, BooleanToEngStr(Symbolic))));
  1267. DoCreateLink(FileName, PointTo, Symbolic);
  1268. ReactOnCommand(fsCreateDirectory);
  1269. }
  1270. //---------------------------------------------------------------------------
  1271. void __fastcall TTerminal::DoCreateLink(const AnsiString FileName,
  1272. const AnsiString PointTo, bool Symbolic)
  1273. {
  1274. try
  1275. {
  1276. assert(FFileSystem);
  1277. FFileSystem->CreateLink(FileName, PointTo, Symbolic);
  1278. }
  1279. catch(Exception & E)
  1280. {
  1281. COMMAND_ERROR_ARI
  1282. (
  1283. FMTLOAD(CREATE_LINK_ERROR, (FileName)),
  1284. DoCreateLink(FileName, PointTo, Symbolic);
  1285. );
  1286. }
  1287. }
  1288. //---------------------------------------------------------------------------
  1289. void __fastcall TTerminal::HomeDirectory()
  1290. {
  1291. assert(FFileSystem);
  1292. try
  1293. {
  1294. LogEvent("Changing directory to home directory.");
  1295. FFileSystem->HomeDirectory();
  1296. ReactOnCommand(fsHomeDirectory);
  1297. }
  1298. catch (Exception &E)
  1299. {
  1300. CommandError(&E, LoadStr(CHANGE_HOMEDIR_ERROR));
  1301. }
  1302. }
  1303. //---------------------------------------------------------------------------
  1304. void __fastcall TTerminal::ChangeDirectory(const AnsiString Directory)
  1305. {
  1306. assert(FFileSystem);
  1307. try
  1308. {
  1309. AnsiString CachedDirectory;
  1310. assert(!SessionData->CacheDirectoryChanges || (FDirectoryChangesCache != NULL));
  1311. if (SessionData->CacheDirectoryChanges &&
  1312. FDirectoryChangesCache->GetDirectoryChange(PeekCurrentDirectory(),
  1313. Directory, CachedDirectory))
  1314. {
  1315. LogEvent(FORMAT("Cached directory change via \"%s\" to \"%s\".",
  1316. (Directory, CachedDirectory)));
  1317. FFileSystem->CachedChangeDirectory(CachedDirectory);
  1318. }
  1319. else
  1320. {
  1321. LogEvent(FORMAT("Changing directory to \"%s\".", (Directory)));
  1322. FFileSystem->ChangeDirectory(Directory);
  1323. }
  1324. FLastDirectoryChange = Directory;
  1325. ReactOnCommand(fsChangeDirectory);
  1326. }
  1327. catch (Exception &E)
  1328. {
  1329. CommandError(&E, FMTLOAD(CHANGE_DIR_ERROR, (Directory)));
  1330. }
  1331. }
  1332. //---------------------------------------------------------------------------
  1333. void __fastcall TTerminal::LookupUsersGroups()
  1334. {
  1335. assert(FFileSystem);
  1336. assert(IsCapable[fcUserGroupListing]);
  1337. try
  1338. {
  1339. FUsersGroupsLookedup = true;
  1340. LogEvent("Looking up groups and users.");
  1341. FFileSystem->LookupUsersGroups();
  1342. ReactOnCommand(fsLookupUsersGroups);
  1343. if (IsLogging())
  1344. {
  1345. if (FGroups->Count > 0)
  1346. {
  1347. LogEvent("Following groups found:");
  1348. for (int Index = 0; Index < FGroups->Count; Index++)
  1349. {
  1350. LogEvent(AnsiString(" ") + FGroups->Strings[Index]);
  1351. }
  1352. }
  1353. else
  1354. {
  1355. LogEvent("No groups found.");
  1356. }
  1357. if (FUsers->Count > 0)
  1358. {
  1359. LogEvent("Following users found:");
  1360. for (int Index = 0; Index < FUsers->Count; Index++)
  1361. {
  1362. LogEvent(AnsiString(" ") + FUsers->Strings[Index]);
  1363. }
  1364. }
  1365. else
  1366. {
  1367. LogEvent("No users found.");
  1368. }
  1369. }
  1370. }
  1371. catch (Exception &E)
  1372. {
  1373. CommandError(&E, LoadStr(LOOKUP_GROUPS_ERROR));
  1374. }
  1375. }
  1376. //---------------------------------------------------------------------------
  1377. bool __fastcall TTerminal::AllowedAnyCommand(const AnsiString Command)
  1378. {
  1379. return !Command.Trim().IsEmpty();
  1380. }
  1381. //---------------------------------------------------------------------------
  1382. void __fastcall TTerminal::AnyCommand(const AnsiString Command)
  1383. {
  1384. assert(FFileSystem);
  1385. try
  1386. {
  1387. DirectoryModified(CurrentDirectory, false);
  1388. LogEvent("Executing used defined command.");
  1389. FFileSystem->AnyCommand(Command);
  1390. ReactOnCommand(fsAnyCommand);
  1391. }
  1392. catch (Exception &E)
  1393. {
  1394. if (ExceptionOnFail || (E.InheritsFrom(__classid(EFatal)))) throw;
  1395. else DoShowExtendedException(&E);
  1396. }
  1397. }
  1398. //---------------------------------------------------------------------------
  1399. bool __fastcall TTerminal::CreateLocalFile(const AnsiString FileName,
  1400. TFileOperationProgressType * OperationProgress, HANDLE * AHandle)
  1401. {
  1402. assert(AHandle);
  1403. bool Result = true;
  1404. FILE_OPERATION_LOOP (FMTLOAD(CREATE_FILE_ERROR, (FileName)),
  1405. bool Done;
  1406. do
  1407. {
  1408. *AHandle = CreateFile(FileName.c_str(), GENERIC_WRITE, FILE_SHARE_READ,
  1409. NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  1410. Done = (*AHandle != INVALID_HANDLE_VALUE);
  1411. if (!Done)
  1412. {
  1413. int FileAttr;
  1414. if (FileExists(FileName) &&
  1415. (((FileAttr = FileGetAttr(FileName)) & faReadOnly) != 0))
  1416. {
  1417. if (OperationProgress->NoToAll)
  1418. {
  1419. Result = false;
  1420. }
  1421. else if (!OperationProgress->YesToAll)
  1422. {
  1423. int Answer;
  1424. SUSPEND_OPERATION
  1425. (
  1426. Answer = DoQueryUser(
  1427. FMTLOAD(READ_ONLY_OVERWRITE, (FileName)),
  1428. qaYes | qaNo | qaAbort | qaYesToAll | qaNoToAll, 0);
  1429. );
  1430. switch (Answer) {
  1431. case qaYesToAll: OperationProgress->YesToAll = true; break;
  1432. case qaAbort: OperationProgress->Cancel = csCancel; // continue on next case
  1433. case qaNoToAll: OperationProgress->NoToAll = true;
  1434. case qaNo: Result = false; break;
  1435. }
  1436. }
  1437. if (Result)
  1438. {
  1439. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (FileName)),
  1440. if (FileSetAttr(FileName, FileAttr & ~faReadOnly) != 0)
  1441. {
  1442. EXCEPTION;
  1443. }
  1444. );
  1445. }
  1446. else
  1447. {
  1448. Done = true;
  1449. }
  1450. }
  1451. else
  1452. {
  1453. EXCEPTION;
  1454. }
  1455. }
  1456. }
  1457. while (!Done);
  1458. );
  1459. return Result;
  1460. }
  1461. //---------------------------------------------------------------------------
  1462. void __fastcall TTerminal::OpenLocalFile(const AnsiString FileName,
  1463. int Access, int * AAttrs, HANDLE * AHandle, unsigned long * ACTime,
  1464. unsigned long * AMTime, unsigned long * AATime, __int64 * ASize,
  1465. bool TryWriteReadOnly)
  1466. {
  1467. int Attrs = 0;
  1468. HANDLE Handle = 0;
  1469. FILE_OPERATION_LOOP (FMTLOAD(FILE_NOT_EXISTS, (FileName)),
  1470. Attrs = FileGetAttr(FileName);
  1471. if (Attrs == -1) EXCEPTION;
  1472. )
  1473. if ((Attrs & faDirectory) == 0)
  1474. {
  1475. bool NoHandle = false;
  1476. if (!TryWriteReadOnly && (Access == GENERIC_WRITE) &&
  1477. ((Attrs & faReadOnly) != 0))
  1478. {
  1479. Access = GENERIC_READ;
  1480. NoHandle = true;
  1481. }
  1482. FILE_OPERATION_LOOP (FMTLOAD(OPENFILE_ERROR, (FileName)),
  1483. Handle = CreateFile(FileName.c_str(), Access,
  1484. Access == GENERIC_READ ? FILE_SHARE_READ | FILE_SHARE_WRITE : FILE_SHARE_READ,
  1485. NULL, OPEN_EXISTING, 0, 0);
  1486. if (Handle == INVALID_HANDLE_VALUE)
  1487. {
  1488. Handle = 0;
  1489. EXCEPTION;
  1490. }
  1491. );
  1492. try
  1493. {
  1494. if (AATime || AMTime || ACTime)
  1495. {
  1496. // Get last file access and modification time
  1497. FILE_OPERATION_LOOP (FMTLOAD(CANT_GET_ATTRS, (FileName)),
  1498. FILETIME ATime;
  1499. FILETIME MTime;
  1500. FILETIME CTime;
  1501. if (!GetFileTime(Handle, &CTime, &ATime, &MTime)) EXCEPTION;
  1502. if (ACTime)
  1503. {
  1504. *ACTime = ConvertTimestampToUnix(CTime, SessionData->ConsiderDST);
  1505. }
  1506. if (AATime)
  1507. {
  1508. *AATime = ConvertTimestampToUnix(ATime, SessionData->ConsiderDST);
  1509. }
  1510. if (AMTime)
  1511. {
  1512. *AMTime = ConvertTimestampToUnix(MTime, SessionData->ConsiderDST);
  1513. }
  1514. );
  1515. }
  1516. if (ASize)
  1517. {
  1518. // Get file size
  1519. FILE_OPERATION_LOOP (FMTLOAD(CANT_GET_ATTRS, (FileName)),
  1520. unsigned long LSize;
  1521. unsigned long HSize;
  1522. LSize = GetFileSize(Handle, &HSize);
  1523. if ((LSize == 0xFFFFFFFF) && (GetLastError() != NO_ERROR)) EXCEPTION;
  1524. *ASize = (__int64(HSize) << 32) + LSize;
  1525. );
  1526. }
  1527. if ((AHandle == NULL) || NoHandle)
  1528. {
  1529. CloseHandle(Handle);
  1530. Handle = NULL;
  1531. }
  1532. }
  1533. catch(...)
  1534. {
  1535. CloseHandle(Handle);
  1536. throw;
  1537. }
  1538. }
  1539. if (AAttrs) *AAttrs = Attrs;
  1540. if (AHandle) *AHandle = Handle;
  1541. }
  1542. //---------------------------------------------------------------------------
  1543. void __fastcall TTerminal::CalculateLocalFileSize(const AnsiString FileName,
  1544. const TSearchRec Rec, /*__int64*/ void * Size)
  1545. {
  1546. if ((Rec.Attr & faDirectory) == 0)
  1547. {
  1548. (*static_cast<__int64*>(Size)) +=
  1549. (static_cast<__int64>(Rec.FindData.nFileSizeHigh) << 32) +
  1550. Rec.FindData.nFileSizeLow;
  1551. }
  1552. if (OperationProgress && OperationProgress->Operation == foCalculateSize)
  1553. {
  1554. if (OperationProgress->Cancel != csContinue) Abort();
  1555. OperationProgress->SetFile(FileName);
  1556. }
  1557. }
  1558. //---------------------------------------------------------------------------
  1559. void __fastcall TTerminal::CalculateLocalFilesSize(TStrings * FileList, __int64 & Size)
  1560. {
  1561. Size = 0;
  1562. TFileOperationProgressType OperationProgress(FOnProgress, FOnFinished);
  1563. OperationProgress.Start(foCalculateSize, osLocal, FileList->Count);
  1564. try
  1565. {
  1566. assert(!FOperationProgress);
  1567. FOperationProgress = &OperationProgress;
  1568. TSearchRec Rec;
  1569. for (int Index = 0; Index < FileList->Count; Index++)
  1570. {
  1571. if (FileSearchRec(FileList->Strings[Index], Rec))
  1572. {
  1573. if (Rec.Attr & faDirectory)
  1574. {
  1575. ProcessLocalDirectory(FileList->Strings[Index],
  1576. CalculateLocalFileSize, &Size);
  1577. }
  1578. CalculateLocalFileSize(FileList->Strings[Index], Rec, &Size);
  1579. }
  1580. }
  1581. }
  1582. __finally
  1583. {
  1584. FOperationProgress = NULL;
  1585. OperationProgress.Stop();
  1586. }
  1587. }
  1588. //---------------------------------------------------------------------------
  1589. struct TSynchronizeFileData
  1590. {
  1591. int Time;
  1592. int Attr;
  1593. unsigned long SizeHigh;
  1594. unsigned long SizeLow;
  1595. FILETIME LastWriteTime;
  1596. bool Modified;
  1597. bool New;
  1598. };
  1599. //---------------------------------------------------------------------------
  1600. struct TSynchronizeData
  1601. {
  1602. AnsiString LocalDirectory;
  1603. AnsiString RemoteDirectory;
  1604. TTerminal::TSynchronizeMode Mode;
  1605. int Params;
  1606. TSynchronizeDirectory OnSynchronizeDirectory;
  1607. TStringList * LocalFileList;
  1608. TStringList * ModifiedRemoteFileList;
  1609. TStringList * NewRemoteFileList;
  1610. const TCopyParamType * CopyParam;
  1611. };
  1612. //---------------------------------------------------------------------------
  1613. void __fastcall TTerminal::Synchronize(const AnsiString LocalDirectory,
  1614. const AnsiString RemoteDirectory, TSynchronizeMode Mode,
  1615. const TCopyParamType * CopyParam, int Params,
  1616. TSynchronizeDirectory OnSynchronizeDirectory)
  1617. {
  1618. assert(CopyParam != NULL);
  1619. TCopyParamType SyncCopyParam = *CopyParam;
  1620. SyncCopyParam.PreserveTime = true;
  1621. BeginTransaction();
  1622. try
  1623. {
  1624. DoSynchronizeDirectory(LocalDirectory, RemoteDirectory, Mode,
  1625. &SyncCopyParam, Params, OnSynchronizeDirectory);
  1626. }
  1627. __finally
  1628. {
  1629. EndTransaction();
  1630. }
  1631. }
  1632. //---------------------------------------------------------------------------
  1633. void __fastcall TTerminal::DoSynchronizeDirectory(const AnsiString LocalDirectory,
  1634. const AnsiString RemoteDirectory, TSynchronizeMode Mode,
  1635. const TCopyParamType * CopyParam, int Params,
  1636. TSynchronizeDirectory OnSynchronizeDirectory)
  1637. {
  1638. TSearchRec SearchRec;
  1639. bool Found;
  1640. bool Delete = (Params & spDelete) != 0;
  1641. TSynchronizeData Data;
  1642. Data.LocalDirectory = IncludeTrailingBackslash(LocalDirectory);
  1643. Data.RemoteDirectory = UnixIncludeTrailingBackslash(RemoteDirectory);
  1644. Data.Mode = Mode;
  1645. Data.Params = Params;
  1646. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  1647. Data.LocalFileList = NULL;
  1648. Data.NewRemoteFileList = NULL;
  1649. Data.ModifiedRemoteFileList = NULL;
  1650. Data.CopyParam = CopyParam;
  1651. TStrings * LocalFileList = NULL;
  1652. LogEvent(FORMAT("Synchronizing local directory '%s' with remote directory '%s', "
  1653. "mode = %d, params = %d", (LocalDirectory, RemoteDirectory,
  1654. int(Mode), int(Params))));
  1655. bool Continue = true;
  1656. OnSynchronizeDirectory(LocalDirectory, RemoteDirectory, Continue);
  1657. if (!Continue)
  1658. {
  1659. Abort();
  1660. }
  1661. try
  1662. {
  1663. Data.LocalFileList = new TStringList();
  1664. Data.LocalFileList->Sorted = true;
  1665. Data.LocalFileList->CaseSensitive = false;
  1666. Data.NewRemoteFileList = new TStringList();
  1667. Data.ModifiedRemoteFileList = new TStringList();
  1668. LocalFileList = new TStringList();
  1669. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (LocalDirectory)),
  1670. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1671. Found = (FindFirst(Data.LocalDirectory + "*.*", FindAttrs, SearchRec) == 0);
  1672. );
  1673. if (Found)
  1674. {
  1675. try
  1676. {
  1677. AnsiString FileName;
  1678. while (Found)
  1679. {
  1680. FileName = SearchRec.Name;
  1681. if ((FileName != ".") && (FileName != ".."))
  1682. {
  1683. TSynchronizeFileData * FileData = new TSynchronizeFileData;
  1684. FileData->Time = SearchRec.Time;
  1685. FileData->SizeHigh = SearchRec.FindData.nFileSizeHigh;
  1686. FileData->SizeLow = SearchRec.FindData.nFileSizeLow;
  1687. FileData->Attr = SearchRec.Attr;
  1688. FileData->LastWriteTime = SearchRec.FindData.ftLastWriteTime;
  1689. FileData->New = true;
  1690. FileData->Modified = false;
  1691. Data.LocalFileList->AddObject(FileName,
  1692. reinterpret_cast<TObject*>(FileData));
  1693. }
  1694. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (LocalDirectory)),
  1695. Found = (FindNext(SearchRec) == 0);
  1696. );
  1697. }
  1698. }
  1699. __finally
  1700. {
  1701. FindClose(SearchRec);
  1702. }
  1703. ProcessDirectory(RemoteDirectory, SynchronizeFile, &Data);
  1704. TSynchronizeFileData * FileData;
  1705. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  1706. {
  1707. FileData = reinterpret_cast<TSynchronizeFileData *>
  1708. (Data.LocalFileList->Objects[Index]);
  1709. if ((FileData->Modified && ((Mode == smBoth) || (Mode == smRemote))) ||
  1710. (FileData->New))
  1711. {
  1712. LocalFileList->Add(Data.LocalDirectory + Data.LocalFileList->Strings[Index]);
  1713. }
  1714. }
  1715. int CopyParams = (Params & spNoConfirmation) != 0 ? cpNoConfirmation : 0;
  1716. if (LocalFileList->Count > 0)
  1717. {
  1718. bool Result;
  1719. if ((Mode == smBoth) || (Mode == smRemote))
  1720. {
  1721. Result = CopyToRemote(LocalFileList, RemoteDirectory, CopyParam, CopyParams);
  1722. }
  1723. else if ((Mode == smLocal) && Delete)
  1724. {
  1725. Result = DeleteLocalFiles(LocalFileList);
  1726. }
  1727. if (!Result)
  1728. {
  1729. Abort();
  1730. }
  1731. }
  1732. if ((Mode == smBoth) || (Mode == smLocal))
  1733. {
  1734. Data.ModifiedRemoteFileList->AddStrings(Data.NewRemoteFileList);
  1735. if (Data.ModifiedRemoteFileList->Count > 0)
  1736. {
  1737. if (!CopyToLocal(Data.ModifiedRemoteFileList, LocalDirectory,
  1738. CopyParam, CopyParams))
  1739. {
  1740. Abort();
  1741. }
  1742. }
  1743. }
  1744. if ((Mode == smRemote) && Delete && (Data.NewRemoteFileList->Count > 0))
  1745. {
  1746. if (!DeleteFiles(Data.NewRemoteFileList))
  1747. {
  1748. Abort();
  1749. }
  1750. }
  1751. }
  1752. }
  1753. __finally
  1754. {
  1755. if (Data.LocalFileList != NULL)
  1756. {
  1757. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  1758. {
  1759. delete reinterpret_cast<TSynchronizeFileData*>
  1760. (Data.LocalFileList->Objects[Index]);
  1761. }
  1762. delete Data.LocalFileList;
  1763. }
  1764. TStringList * FileList = Data.NewRemoteFileList;
  1765. while (FileList != Data.ModifiedRemoteFileList)
  1766. {
  1767. if (FileList != NULL)
  1768. {
  1769. for (int Index = 0; Index < FileList->Count; Index++)
  1770. {
  1771. delete static_cast<TRemoteFile*>(FileList->Objects[Index]);
  1772. }
  1773. delete FileList;
  1774. }
  1775. FileList = Data.ModifiedRemoteFileList;
  1776. }
  1777. delete LocalFileList;
  1778. }
  1779. }
  1780. //---------------------------------------------------------------------------
  1781. void __fastcall TTerminal::SynchronizeFile(const AnsiString FileName,
  1782. const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
  1783. {
  1784. TSynchronizeData * Data = static_cast<TSynchronizeData *>(Param);
  1785. bool Modified = false;
  1786. int Index = Data->LocalFileList->IndexOf(File->FileName);
  1787. bool New = (Index < 0);
  1788. if (!New)
  1789. {
  1790. TSynchronizeFileData * LocalData =
  1791. reinterpret_cast<TSynchronizeFileData *>(Data->LocalFileList->Objects[Index]);
  1792. LocalData->New = false;
  1793. bool LocalDirectory = (LocalData->Attr & faDirectory) != 0;
  1794. if (File->IsDirectory != LocalDirectory)
  1795. {
  1796. LogEvent(FORMAT("%s is directory on one side, but file on the another",
  1797. (File->FileName)));
  1798. }
  1799. else if (!File->IsDirectory)
  1800. {
  1801. FILETIME LocalLastWriteTime;
  1802. SYSTEMTIME SystemLastWriteTime;
  1803. FileTimeToLocalFileTime(&LocalData->LastWriteTime, &LocalLastWriteTime);
  1804. FileTimeToSystemTime(&LocalLastWriteTime, &SystemLastWriteTime);
  1805. TDateTime LocalTime = SystemTimeToDateTime(SystemLastWriteTime);
  1806. TDateTime RemoteTime = File->Modification;
  1807. UnifyDateTimePrecision(LocalTime, RemoteTime);
  1808. if (LocalTime < RemoteTime)
  1809. {
  1810. Modified = true;
  1811. }
  1812. else if (LocalTime > RemoteTime)
  1813. {
  1814. LocalData->Modified = true;
  1815. }
  1816. }
  1817. else
  1818. {
  1819. DoSynchronizeDirectory(
  1820. Data->LocalDirectory + File->FileName,
  1821. Data->RemoteDirectory + File->FileName,
  1822. Data->Mode, Data->CopyParam, Data->Params, Data->OnSynchronizeDirectory);
  1823. }
  1824. }
  1825. if (New || Modified)
  1826. {
  1827. assert(!New || !Modified);
  1828. TStringList * FileList = New ? Data->NewRemoteFileList :
  1829. Data->ModifiedRemoteFileList;
  1830. FileList->AddObject(FileName,
  1831. const_cast<TRemoteFile *>(File)->Duplicate());
  1832. }
  1833. }
  1834. //---------------------------------------------------------------------------
  1835. bool __fastcall TTerminal::CopyToRemote(TStrings * FilesToCopy,
  1836. const AnsiString TargetDir, const TCopyParamType * CopyParam, int Params)
  1837. {
  1838. assert(FFileSystem);
  1839. assert(FilesToCopy);
  1840. bool Result = false;
  1841. bool DisconnectWhenComplete = false;
  1842. try
  1843. {
  1844. __int64 Size;
  1845. if (CopyParam->CalculateSize)
  1846. {
  1847. CalculateLocalFilesSize(FilesToCopy, Size);
  1848. }
  1849. TFileOperationProgressType OperationProgress(FOnProgress, FOnFinished);
  1850. OperationProgress.Start((Params & cpDelete ? foMove : foCopy), osLocal,
  1851. FilesToCopy->Count, Params & cpDragDrop, TargetDir);
  1852. if (CopyParam->CalculateSize)
  1853. {
  1854. OperationProgress.SetTotalSize(Size);
  1855. }
  1856. FOperationProgress = &OperationProgress;
  1857. try
  1858. {
  1859. AnsiString UnlockedTargetDir = TranslateLockedPath(TargetDir, false);
  1860. BeginTransaction();
  1861. try
  1862. {
  1863. if (IsLogging())
  1864. {
  1865. LogEvent(FORMAT("Copying %d files/directories to remote directory "
  1866. "\"%s\"", (FilesToCopy->Count, TargetDir)));
  1867. LogEvent(CopyParam->LogStr);
  1868. }
  1869. FFileSystem->CopyToRemote(FilesToCopy, UnlockedTargetDir,
  1870. CopyParam, Params, &OperationProgress, DisconnectWhenComplete);
  1871. }
  1872. __finally
  1873. {
  1874. if (Active)
  1875. {
  1876. ReactOnCommand(fsCopyToRemote);
  1877. EndTransaction();
  1878. }
  1879. }
  1880. if (OperationProgress.Cancel == csContinue)
  1881. {
  1882. Result = true;
  1883. }
  1884. }
  1885. __finally
  1886. {
  1887. OperationProgress.Stop();
  1888. FOperationProgress = NULL;
  1889. }
  1890. }
  1891. catch (Exception &E)
  1892. {
  1893. CommandError(&E, LoadStr(TOREMOTE_COPY_ERROR));
  1894. DisconnectWhenComplete = false;
  1895. }
  1896. if (DisconnectWhenComplete) CloseOnCompletion();
  1897. return Result;
  1898. }
  1899. //---------------------------------------------------------------------------
  1900. bool __fastcall TTerminal::CopyToLocal(TStrings * FilesToCopy,
  1901. const AnsiString TargetDir, const TCopyParamType * CopyParam, int Params)
  1902. {
  1903. assert(FFileSystem);
  1904. // see scp.c: sink(), tolocal()
  1905. bool Result = false;
  1906. bool OwnsFileList = (FilesToCopy == NULL);
  1907. bool DisconnectWhenComplete = false;
  1908. try
  1909. {
  1910. if (OwnsFileList)
  1911. {
  1912. FilesToCopy = new TStringList();
  1913. FilesToCopy->Assign(Files->SelectedFiles);
  1914. }
  1915. BeginTransaction();
  1916. try
  1917. {
  1918. __int64 TotalSize;
  1919. bool TotalSizeKnown = false;
  1920. TFileOperationProgressType OperationProgress(FOnProgress, FOnFinished);
  1921. if (CopyParam->CalculateSize)
  1922. {
  1923. ExceptionOnFail = true;
  1924. try
  1925. {
  1926. CalculateFilesSize(FilesToCopy, TotalSize, csIgnoreErrors);
  1927. TotalSizeKnown = true;
  1928. }
  1929. __finally
  1930. {
  1931. ExceptionOnFail = false;
  1932. }
  1933. }
  1934. OperationProgress.Start((Params & cpDelete ? foMove : foCopy), osRemote,
  1935. FilesToCopy->Count, Params & cpDragDrop, TargetDir);
  1936. if (TotalSizeKnown)
  1937. {
  1938. OperationProgress.SetTotalSize(TotalSize);
  1939. }
  1940. FOperationProgress = &OperationProgress;
  1941. try
  1942. {
  1943. try
  1944. {
  1945. try
  1946. {
  1947. FFileSystem->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params,
  1948. &OperationProgress, DisconnectWhenComplete);
  1949. }
  1950. __finally
  1951. {
  1952. if (Active)
  1953. {
  1954. ReactOnCommand(fsCopyToLocal);
  1955. }
  1956. }
  1957. }
  1958. catch (Exception &E)
  1959. {
  1960. CommandError(&E, LoadStr(TOLOCAL_COPY_ERROR));
  1961. DisconnectWhenComplete = false;
  1962. }
  1963. if (OperationProgress.Cancel == csContinue)
  1964. {
  1965. Result = true;
  1966. }
  1967. }
  1968. __finally
  1969. {
  1970. FOperationProgress = NULL;
  1971. OperationProgress.Stop();
  1972. }
  1973. }
  1974. __finally
  1975. {
  1976. // If session is still active (no fatal error) we reload directory
  1977. // by calling EndTransaction
  1978. EndTransaction();
  1979. }
  1980. }
  1981. __finally
  1982. {
  1983. if (OwnsFileList) delete FilesToCopy;
  1984. }
  1985. if (DisconnectWhenComplete) CloseOnCompletion();
  1986. return Result;
  1987. }
  1988. //---------------------------------------------------------------------------
  1989. __fastcall TTerminalList::TTerminalList(TConfiguration * AConfiguration) :
  1990. TObjectList()
  1991. {
  1992. assert(AConfiguration);
  1993. FConfiguration = AConfiguration;
  1994. }
  1995. //---------------------------------------------------------------------------
  1996. __fastcall TTerminalList::~TTerminalList()
  1997. {
  1998. assert(Count == 0);
  1999. }
  2000. //---------------------------------------------------------------------------
  2001. TTerminal * __fastcall TTerminalList::NewTerminal(TSessionData * Data)
  2002. {
  2003. TTerminal * Terminal = new TTerminal();
  2004. try
  2005. {
  2006. Terminal->Configuration = FConfiguration;
  2007. Terminal->SessionData = Data;
  2008. Add(Terminal);
  2009. }
  2010. catch(...)
  2011. {
  2012. delete Terminal;
  2013. throw;
  2014. }
  2015. return Terminal;
  2016. }
  2017. //---------------------------------------------------------------------------
  2018. void __fastcall TTerminalList::FreeTerminal(TTerminal * Terminal)
  2019. {
  2020. assert(IndexOf(Terminal) >= 0);
  2021. Remove(Terminal);
  2022. }
  2023. //---------------------------------------------------------------------------
  2024. void __fastcall TTerminalList::FreeAndNullTerminal(TTerminal * & Terminal)
  2025. {
  2026. TTerminal * T = Terminal;
  2027. Terminal = NULL;
  2028. FreeTerminal(T);
  2029. }
  2030. //---------------------------------------------------------------------------
  2031. TTerminal * __fastcall TTerminalList::GetTerminal(int Index)
  2032. {
  2033. return dynamic_cast<TTerminal *>(Items[Index]);
  2034. }
  2035. //---------------------------------------------------------------------------
  2036. void __fastcall TTerminalList::Idle()
  2037. {
  2038. TTerminal * Terminal;
  2039. for (int i = 0; i < Count; i++)
  2040. {
  2041. Terminal = Terminals[i];
  2042. if (Terminal->Status == sshReady)
  2043. {
  2044. Terminal->Idle();
  2045. }
  2046. }
  2047. }