Terminal.cpp 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283
  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. //---------------------------------------------------------------------------
  27. __fastcall TTerminal::TTerminal(): TSecureShell()
  28. {
  29. FFiles = new TRemoteDirectory(this);
  30. FExceptionOnFail = 0;
  31. FInTransaction = 0;
  32. FReadCurrentDirectoryPending = false;
  33. FReadDirectoryPending = false;
  34. FUserGroupsLookedup = False;
  35. FUserGroups = new TUserGroupsList();
  36. FOnProgress = NULL;
  37. FOnFinished = NULL;
  38. FUseBusyCursor = True;
  39. FLockDirectory = "";
  40. FDirectoryCache = new TRemoteDirectoryCache();
  41. }
  42. //---------------------------------------------------------------------------
  43. __fastcall TTerminal::~TTerminal()
  44. {
  45. SAFE_DESTROY(FFileSystem);
  46. delete FFiles;
  47. delete FUserGroups;
  48. delete FDirectoryCache;
  49. }
  50. //---------------------------------------------------------------------------
  51. AnsiString __fastcall TTerminal::GetProtocolName()
  52. {
  53. assert(FFileSystem);
  54. return FFileSystem->ProtocolName;
  55. }
  56. //---------------------------------------------------------------------------
  57. void __fastcall TTerminal::Close()
  58. {
  59. // file system cannot be destoryed here, moved to destructor
  60. TSecureShell::Close();
  61. }
  62. //---------------------------------------------------------------------------
  63. void __fastcall TTerminal::Open()
  64. {
  65. TSecureShell::Open();
  66. assert(!FFileSystem);
  67. if ((SessionData->FSProtocol == fsSCPonly) ||
  68. (SessionData->FSProtocol == fsSFTP && SshFallbackCmd()))
  69. {
  70. FFileSystem = new TSCPFileSystem(this);
  71. LogEvent("Using SCP protocol.");
  72. }
  73. else
  74. {
  75. FFileSystem = new TSFTPFileSystem(this);
  76. LogEvent("Using SFTP protocol.");
  77. }
  78. }
  79. //---------------------------------------------------------------------------
  80. bool __fastcall TTerminal::GetIsCapable(TFSCapability Capability) const
  81. {
  82. assert(FFileSystem);
  83. return FFileSystem->IsCapable(Capability);
  84. }
  85. //---------------------------------------------------------------------------
  86. void __fastcall TTerminal::ReactOnCommand(int /*TFSCommand*/ Cmd)
  87. {
  88. bool ChangesDirectory = false;
  89. bool ModifiesFiles = false;
  90. switch ((TFSCommand)Cmd) {
  91. case fsChangeDirectory:
  92. case fsHomeDirectory:
  93. ChangesDirectory = true;
  94. break;
  95. case fsCopyToRemote:
  96. case fsDeleteFile:
  97. case fsRenameFile:
  98. case fsCreateDirectory:
  99. case fsChangeMode:
  100. case fsChangeGroup:
  101. case fsChangeOwner:
  102. case fsChangeProperties:
  103. case fsAnyCommand:
  104. ModifiesFiles = true;
  105. break;
  106. }
  107. if (ChangesDirectory)
  108. {
  109. if (!FInTransaction)
  110. {
  111. ReadCurrentDirectory();
  112. ReadDirectory(false);
  113. }
  114. else
  115. {
  116. FReadCurrentDirectoryPending = true;
  117. FReadDirectoryPending = true;
  118. }
  119. }
  120. else
  121. if (ModifiesFiles)
  122. {
  123. if (!FInTransaction) ReadDirectory(true);
  124. else FReadDirectoryPending = true;
  125. }
  126. }
  127. //---------------------------------------------------------------------------
  128. void __fastcall TTerminal::TerminalError(AnsiString Msg)
  129. {
  130. TerminalError(NULL, Msg);
  131. }
  132. //---------------------------------------------------------------------------
  133. void __fastcall TTerminal::TerminalError(Exception * E, AnsiString Msg)
  134. {
  135. throw ETerminal(E, Msg);
  136. }
  137. //---------------------------------------------------------------------------
  138. int __fastcall TTerminal::FileOperationLoop(TFileOperationEvent CallBackFunc,
  139. TFileOperationProgressType * OperationProgress, bool AllowSkip,
  140. const AnsiString Message, void * Param1, void * Param2)
  141. {
  142. assert(CallBackFunc);
  143. int Result;
  144. TTerminal * FTerminal = this; // required by FILE_OPERATION_LOOP_EX macro
  145. FILE_OPERATION_LOOP_EX
  146. (
  147. "", AllowSkip, Message,
  148. Result = CallBackFunc(Param1, Param2);
  149. );
  150. return Result;
  151. }
  152. //---------------------------------------------------------------------------
  153. AnsiString __fastcall TTerminal::TranslateLockedPath(AnsiString Path, bool Lock)
  154. {
  155. if (!SessionData->LockInHome || Path.IsEmpty() || (Path[1] != '/'))
  156. return Path;
  157. if (Lock)
  158. {
  159. if (Path.SubString(1, FLockDirectory.Length()) == FLockDirectory)
  160. {
  161. Path.Delete(1, FLockDirectory.Length());
  162. if (Path.IsEmpty()) Path = "/";
  163. }
  164. }
  165. else
  166. {
  167. Path = UnixExcludeTrailingBackslash(FLockDirectory + Path);
  168. }
  169. return Path;
  170. }
  171. //---------------------------------------------------------------------------
  172. void __fastcall TTerminal::SetCurrentDirectory(AnsiString value)
  173. {
  174. assert(FFileSystem);
  175. value = TranslateLockedPath(value, false);
  176. if (value != FFileSystem->CurrentDirectory)
  177. {
  178. ChangeDirectory(value);
  179. }
  180. }
  181. //---------------------------------------------------------------------------
  182. AnsiString __fastcall TTerminal::GetCurrentDirectory()
  183. {
  184. if (FFileSystem)
  185. {
  186. FCurrentDirectory = FFileSystem->CurrentDirectory;
  187. if (FCurrentDirectory.IsEmpty())
  188. {
  189. ReadCurrentDirectory();
  190. }
  191. }
  192. return TranslateLockedPath(FCurrentDirectory, true);
  193. }
  194. //---------------------------------------------------------------------------
  195. TUserGroupsList * __fastcall TTerminal::GetUserGroups()
  196. {
  197. assert(FFileSystem);
  198. if (!FUserGroupsLookedup && SessionData->LookupUserGroups &&
  199. IsCapable[fcUserGroupListing])
  200. {
  201. LookupUserGroups();
  202. }
  203. return FUserGroups;
  204. }
  205. //---------------------------------------------------------------------------
  206. AnsiString __fastcall TTerminal::GetUserName() const
  207. {
  208. // in future might be implemented to detect username similar to GetUserGroups
  209. return SessionData->UserName;
  210. }
  211. //---------------------------------------------------------------------------
  212. void __fastcall TTerminal::DoChangeDirectory()
  213. {
  214. if (FOnChangeDirectory) FOnChangeDirectory(this);
  215. }
  216. //---------------------------------------------------------------------------
  217. void __fastcall TTerminal::DoReadDirectory(bool ReloadOnly)
  218. {
  219. if (FOnReadDirectory) FOnReadDirectory(this, ReloadOnly);
  220. }
  221. //---------------------------------------------------------------------------
  222. void __fastcall TTerminal::BeginTransaction()
  223. {
  224. if (!FInTransaction)
  225. {
  226. FReadCurrentDirectoryPending = false;
  227. FReadDirectoryPending = false;
  228. }
  229. FInTransaction++;
  230. }
  231. //---------------------------------------------------------------------------
  232. void __fastcall TTerminal::EndTransaction()
  233. {
  234. // it connection was closed due to fatal error during transaction, do nothing
  235. if (Active)
  236. {
  237. if (!FInTransaction)
  238. TerminalError("Can't end transaction, not in transaction");
  239. assert(FInTransaction > 0);
  240. FInTransaction--;
  241. if (FInTransaction == 0)
  242. {
  243. try
  244. {
  245. if (FReadCurrentDirectoryPending) ReadCurrentDirectory();
  246. if (FReadDirectoryPending) ReadDirectory(!FReadCurrentDirectoryPending);
  247. }
  248. __finally
  249. {
  250. FReadCurrentDirectoryPending = false;
  251. FReadDirectoryPending = false;
  252. }
  253. }
  254. }
  255. }
  256. //---------------------------------------------------------------------------
  257. void __fastcall TTerminal::SetExceptionOnFail(bool value)
  258. {
  259. if (value) FExceptionOnFail++;
  260. else
  261. {
  262. if (FExceptionOnFail == 0)
  263. throw Exception("ExceptionOnFail is already zero.");
  264. FExceptionOnFail--;
  265. }
  266. }
  267. //---------------------------------------------------------------------------
  268. bool __fastcall TTerminal::GetExceptionOnFail() const
  269. {
  270. return (bool)(FExceptionOnFail > 0);
  271. }
  272. //---------------------------------------------------------------------------
  273. void __fastcall TTerminal::CommandError(Exception * E, const AnsiString Msg)
  274. {
  275. CommandError(E, Msg, 0);
  276. }
  277. //---------------------------------------------------------------------------
  278. int __fastcall TTerminal::CommandError(Exception * E, const AnsiString Msg,
  279. int Answers)
  280. {
  281. int Result = 0;
  282. if (E && E->InheritsFrom(__classid(EFatal)))
  283. {
  284. FatalError(E, Msg);
  285. }
  286. else if (E && E->InheritsFrom(__classid(EAbort)))
  287. {
  288. // resent EAbort exception
  289. Abort();
  290. }
  291. else if (ExceptionOnFail)
  292. {
  293. throw ECommand(E, Msg);
  294. }
  295. else if (!Answers)
  296. {
  297. ECommand * ECmd = new ECommand(E, Msg);
  298. try
  299. {
  300. ShowExtendedException(ECmd, this);
  301. }
  302. __finally
  303. {
  304. delete ECmd;
  305. }
  306. }
  307. else
  308. {
  309. Result = DoQueryUser(Msg, E, Answers, qpAllowContinueOnError);
  310. }
  311. return Result;
  312. }
  313. //---------------------------------------------------------------------------
  314. bool __fastcall TTerminal::HandleException(Exception * E)
  315. {
  316. if (ExceptionOnFail)
  317. {
  318. return false;
  319. }
  320. else
  321. {
  322. HandleExtendedException(E, this);
  323. return true;
  324. }
  325. }
  326. //---------------------------------------------------------------------------
  327. void __fastcall TTerminal::CloseOnCompletion(const AnsiString Message)
  328. {
  329. LogEvent("Closing session after completed operation (as requested by user)");
  330. Close();
  331. throw ESshTerminate(NULL,
  332. Message.IsEmpty() ? LoadStr(CLOSED_ON_COMPLETION) : Message);
  333. }
  334. //---------------------------------------------------------------------------
  335. void __fastcall TTerminal::FileModified(const TRemoteFile * File)
  336. {
  337. assert(File);
  338. if (SessionData->CacheDirectories && File->Directory)
  339. {
  340. if (File->IsDirectory)
  341. {
  342. // do not use UnixIncludeTrailingBackslash(CurrentDirectory)
  343. FDirectoryCache->ClearFileList(
  344. File->Directory->FullDirectory + File->FileName, true);
  345. }
  346. FDirectoryCache->ClearFileList(File->Directory->Directory, false);
  347. }
  348. }
  349. //---------------------------------------------------------------------------
  350. void __fastcall TTerminal::DirectoryModified(const AnsiString UnlockedPath, bool SubDirs)
  351. {
  352. FDirectoryCache->ClearFileList(TranslateLockedPath(UnlockedPath, true),
  353. SubDirs);
  354. }
  355. //---------------------------------------------------------------------------
  356. void __fastcall TTerminal::ReloadDirectory()
  357. {
  358. if (SessionData->CacheDirectories)
  359. {
  360. FDirectoryCache->ClearFileList(CurrentDirectory, false);
  361. }
  362. ReadCurrentDirectory();
  363. FReadCurrentDirectoryPending = false;
  364. ReadDirectory(True);
  365. FReadDirectoryPending = false;
  366. }
  367. //---------------------------------------------------------------------------
  368. void __fastcall TTerminal::EnsureNonExistence(const AnsiString FileName)
  369. {
  370. // if filename doesn't contain path, we check for existence of file
  371. if ((UnixExtractFileDir(FileName) == FileName) &&
  372. UnixComparePaths(CurrentDirectory, FFiles->Directory))
  373. {
  374. TRemoteFile *File = FFiles->FindFile(FileName);
  375. if (File)
  376. {
  377. if (File->IsDirectory) throw ECommand(NULL, FMTLOAD(RENAME_CREATE_DIR_EXISTS, (FileName)));
  378. else throw ECommand(NULL, FMTLOAD(RENAME_CREATE_FILE_EXISTS, (FileName)));
  379. }
  380. }
  381. }
  382. //---------------------------------------------------------------------------
  383. void __fastcall TTerminal::DoStartup()
  384. {
  385. LogEvent("Doing startup conversation with host.");
  386. BeginTransaction();
  387. try
  388. {
  389. UpdateStatus(sshStartup);
  390. // Make sure that directory would be loaded at last
  391. FReadCurrentDirectoryPending = true;
  392. FReadDirectoryPending = true;
  393. FFileSystem->DoStartup();
  394. if (SessionData->LookupUserGroups && IsCapable[fcUserGroupListing])
  395. {
  396. LookupUserGroups();
  397. }
  398. UpdateStatus(sshOpenDirectory);
  399. if (!SessionData->RemoteDirectory.IsEmpty())
  400. {
  401. ChangeDirectory(SessionData->RemoteDirectory);
  402. }
  403. }
  404. __finally
  405. {
  406. EndTransaction();
  407. }
  408. LogEvent("Startup conversation with host finished.");
  409. UpdateStatus(sshReady);
  410. }
  411. //---------------------------------------------------------------------------
  412. void __fastcall TTerminal::ReadCurrentDirectory()
  413. {
  414. assert(FFileSystem);
  415. try
  416. {
  417. LogEvent("Getting current directory name.");
  418. AnsiString OldDirectory = FFileSystem->CurrentDirectory;
  419. FFileSystem->ReadCurrentDirectory();
  420. ReactOnCommand(fsCurrentDirectory);
  421. if (OldDirectory.IsEmpty())
  422. {
  423. FLockDirectory = (SessionData->LockInHome ?
  424. FFileSystem->CurrentDirectory : AnsiString(""));
  425. }
  426. if (OldDirectory != FFileSystem->CurrentDirectory) DoChangeDirectory();
  427. }
  428. catch (Exception &E)
  429. {
  430. CommandError(&E, LoadStr(READ_CURRENT_DIR_ERROR));
  431. }
  432. }
  433. //---------------------------------------------------------------------------
  434. void __fastcall TTerminal::ReadDirectory(bool ReloadOnly)
  435. {
  436. TRemoteFileList * CachedFileList = NULL;
  437. if (SessionData->CacheDirectories)
  438. {
  439. CachedFileList = FDirectoryCache->GetFileList(CurrentDirectory);
  440. }
  441. if (CachedFileList)
  442. {
  443. CachedFileList->DuplicateTo(FFiles);
  444. DoReadDirectory(ReloadOnly);
  445. LogEvent("Directory content loaded from cache.");
  446. }
  447. else
  448. {
  449. FFiles->Directory = CurrentDirectory;
  450. try
  451. {
  452. try
  453. {
  454. CustomReadDirectory(FFiles);
  455. }
  456. __finally
  457. {
  458. if (Active)
  459. {
  460. // this must be called before error is displayed, otherwise
  461. // TUnixDirView would be drawn with invalid data (it keeps reference
  462. // to already destoroyed old listing)
  463. DoReadDirectory(ReloadOnly);
  464. if (SessionData->CacheDirectories)
  465. {
  466. FDirectoryCache->AddFileList(FFiles);
  467. }
  468. }
  469. }
  470. }
  471. catch (Exception &E)
  472. {
  473. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FFiles->Directory))));
  474. }
  475. }
  476. }
  477. //---------------------------------------------------------------------------
  478. void __fastcall TTerminal::CustomReadDirectory(TRemoteFileList * FileList)
  479. {
  480. assert(FileList);
  481. assert(FFileSystem);
  482. FFileSystem->ReadDirectory(FileList);
  483. ReactOnCommand(fsListDirectory);
  484. }
  485. //---------------------------------------------------------------------------
  486. TRemoteFileList * TTerminal::ReadDirectoryListing(AnsiString Directory)
  487. {
  488. TRemoteFileList * FileList;
  489. try
  490. {
  491. FileList = new TRemoteFileList();
  492. try
  493. {
  494. FileList->Directory = Directory;
  495. AnsiString Directory = UnixIncludeTrailingBackslash(Directory);
  496. ExceptionOnFail = true;
  497. try
  498. {
  499. ReadDirectory(FileList);
  500. }
  501. __finally
  502. {
  503. ExceptionOnFail = false;
  504. }
  505. }
  506. catch(...)
  507. {
  508. delete FileList;
  509. throw;
  510. }
  511. }
  512. catch(Exception & E)
  513. {
  514. COMMAND_ERROR_ARI
  515. (
  516. "",
  517. FileList = ReadDirectoryListing(Directory);
  518. );
  519. }
  520. return FileList;
  521. }
  522. //---------------------------------------------------------------------------
  523. void __fastcall TTerminal::ProcessDirectory(const AnsiString DirName,
  524. TProcessFileEvent CallBackFunc, void * Param)
  525. {
  526. TRemoteFileList * FileList = ReadDirectoryListing(DirName);
  527. try
  528. {
  529. AnsiString Directory = UnixIncludeTrailingBackslash(DirName);
  530. TRemoteFile * File;
  531. for (int Index = 0; Index < FileList->Count; Index++)
  532. {
  533. File = FileList->Files[Index];
  534. if (!File->IsParentDirectory && !File->IsThisDirectory)
  535. {
  536. CallBackFunc(Directory + File->FileName, File, Param);
  537. }
  538. }
  539. }
  540. __finally
  541. {
  542. delete FileList;
  543. }
  544. }
  545. //---------------------------------------------------------------------------
  546. void __fastcall TTerminal::ReadDirectory(TRemoteFileList * FileList)
  547. {
  548. try
  549. {
  550. CustomReadDirectory(FileList);
  551. }
  552. catch (Exception &E)
  553. {
  554. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FileList->Directory))));
  555. }
  556. }
  557. //---------------------------------------------------------------------------
  558. void __fastcall TTerminal::ReadSymlink(TRemoteFile * SymlinkFile,
  559. TRemoteFile *& File)
  560. {
  561. assert(FFileSystem);
  562. try
  563. {
  564. LogEvent(FORMAT("Reading symlink \"%s\".", (SymlinkFile->FileName)));
  565. FFileSystem->ReadSymlink(SymlinkFile, File);
  566. ReactOnCommand(fsReadSymlink);
  567. }
  568. catch (Exception &E)
  569. {
  570. CommandError(&E, FMTLOAD(READ_SYMLINK_ERROR, (SymlinkFile->FileName)));
  571. }
  572. }
  573. //---------------------------------------------------------------------------
  574. void __fastcall TTerminal::ReadFile(const AnsiString FileName,
  575. TRemoteFile *& File)
  576. {
  577. assert(FFileSystem);
  578. File = NULL;
  579. try
  580. {
  581. LogEvent(FORMAT("Listing file \"%s\".", (FileName)));
  582. FFileSystem->ReadFile(FileName, File);
  583. ReactOnCommand(fsListFile);
  584. }
  585. catch (Exception &E)
  586. {
  587. if (File) delete File;
  588. File = NULL;
  589. CommandError(&E, FMTLOAD(LIST_DIR_ERROR, (FileName)));
  590. }
  591. }
  592. //---------------------------------------------------------------------------
  593. void __fastcall TTerminal::ProcessFiles(TStrings * FileList,
  594. TFileOperation Operation, TProcessFileEvent ProcessFile, void * Param)
  595. {
  596. assert(FFileSystem);
  597. assert(FileList);
  598. bool DisconnectWhenComplete = false;
  599. try
  600. {
  601. TFileOperationProgressType Progress(FOnProgress, FOnFinished);
  602. Progress.Start(Operation, osRemote, FileList->Count);
  603. FOperationProgress = &Progress;
  604. try
  605. {
  606. BeginTransaction();
  607. try
  608. {
  609. int Index = 0;
  610. AnsiString FileName;
  611. bool Success;
  612. while ((Index < FileList->Count) && (Progress.Cancel == csContinue))
  613. {
  614. FileName = FileList->Strings[Index];
  615. try
  616. {
  617. Success = false;
  618. ProcessFile(FileName, (TRemoteFile *)FileList->Objects[Index], Param);
  619. Success = true;
  620. }
  621. __finally
  622. {
  623. Progress.Finish(UnixExtractFileName(FileName),
  624. Success, DisconnectWhenComplete);
  625. }
  626. Index++;
  627. }
  628. }
  629. __finally
  630. {
  631. EndTransaction();
  632. }
  633. }
  634. __finally
  635. {
  636. FOperationProgress = NULL;
  637. Progress.Stop();
  638. }
  639. }
  640. catch (...)
  641. {
  642. DisconnectWhenComplete = false;
  643. // this was missing here. was it by purpose?
  644. // without it any error message is lost
  645. throw;
  646. }
  647. if (DisconnectWhenComplete)
  648. {
  649. CloseOnCompletion();
  650. }
  651. }
  652. //---------------------------------------------------------------------------
  653. void __fastcall TTerminal::DeleteFile(AnsiString FileName,
  654. const TRemoteFile * File, void * Recursive)
  655. {
  656. if (FileName.IsEmpty() && File)
  657. {
  658. FileName = File->FileName;
  659. }
  660. if (OperationProgress && OperationProgress->Operation == foDelete)
  661. {
  662. if (OperationProgress->Cancel != csContinue) Abort();
  663. OperationProgress->SetFile(FileName);
  664. }
  665. LogEvent(FORMAT("Deleting file \"%s\".", (FileName)));
  666. if (File) FileModified(File);
  667. DoDeleteFile(FileName, File, Recursive);
  668. ReactOnCommand(fsDeleteFile);
  669. }
  670. //---------------------------------------------------------------------------
  671. void __fastcall TTerminal::DoDeleteFile(const AnsiString FileName,
  672. const TRemoteFile * File, void * Recursive)
  673. {
  674. try
  675. {
  676. assert(FFileSystem);
  677. // 'File' parameter: SFTPFileSystem needs to know if file is file or directory
  678. FFileSystem->DeleteFile(FileName, File,
  679. Recursive ? *((bool*)Recursive) : true);
  680. }
  681. catch(Exception & E)
  682. {
  683. COMMAND_ERROR_ARI
  684. (
  685. FMTLOAD(DELETE_FILE_ERROR, (FileName)),
  686. DoDeleteFile(FileName, File, Recursive)
  687. );
  688. }
  689. }
  690. //---------------------------------------------------------------------------
  691. void __fastcall TTerminal::DeleteFiles(TStrings * FilesToDelete, bool * Recursive)
  692. {
  693. ProcessFiles(FilesToDelete, foDelete, DeleteFile, Recursive);
  694. }
  695. //---------------------------------------------------------------------------
  696. void __fastcall TTerminal::CustomCommandOnFile(AnsiString FileName,
  697. const TRemoteFile * File, void * ACommand)
  698. {
  699. AnsiString Command = *((AnsiString *)ACommand);
  700. if (FileName.IsEmpty() && File)
  701. {
  702. FileName = File->FileName;
  703. }
  704. if (OperationProgress && OperationProgress->Operation == foCustomCommand)
  705. {
  706. if (OperationProgress->Cancel != csContinue) Abort();
  707. OperationProgress->SetFile(FileName);
  708. }
  709. LogEvent(FORMAT("Executing custom command \"%s\" on file \"%s\".",
  710. (Command, FileName)));
  711. if (File) FileModified(File);
  712. DoCustomCommandOnFile(FileName, File, Command);
  713. ReactOnCommand(fsAnyCommand);
  714. }
  715. //---------------------------------------------------------------------------
  716. void __fastcall TTerminal::DoCustomCommandOnFile(AnsiString FileName,
  717. const TRemoteFile * File, AnsiString Command)
  718. {
  719. try
  720. {
  721. assert(FFileSystem);
  722. FFileSystem->CustomCommandOnFile(FileName, File, Command);
  723. }
  724. catch(Exception & E)
  725. {
  726. COMMAND_ERROR_ARI
  727. (
  728. FMTLOAD(CUSTOM_COMMAND_ERROR, (Command, FileName)),
  729. DoCustomCommandOnFile(FileName, File, Command)
  730. );
  731. }
  732. }
  733. //---------------------------------------------------------------------------
  734. void __fastcall TTerminal::CustomCommandOnFiles(AnsiString Command, TStrings * Files)
  735. {
  736. ProcessFiles(Files, foCustomCommand, CustomCommandOnFile, &Command);
  737. }
  738. //---------------------------------------------------------------------------
  739. void __fastcall TTerminal::ChangeFileProperties(AnsiString FileName,
  740. const TRemoteFile * File, /*const TRemoteProperties*/ void * Properties)
  741. {
  742. TRemoteProperties * RProperties = (TRemoteProperties *)Properties;
  743. assert(RProperties && !RProperties->Valid.Empty());
  744. if (FileName.IsEmpty() && File)
  745. {
  746. FileName = File->FileName;
  747. }
  748. if (OperationProgress && OperationProgress->Operation == foSetProperties)
  749. {
  750. if (OperationProgress->Cancel != csContinue) Abort();
  751. OperationProgress->SetFile(FileName);
  752. }
  753. if (IsLogging())
  754. {
  755. LogEvent(FORMAT("Changing properties of \"%s\" (%s)",
  756. (FileName, BooleanToEngStr(RProperties->Recursive))));
  757. if (RProperties->Valid.Contains(vpRights))
  758. {
  759. LogEvent(FORMAT(" - mode: \"%s\"", (RProperties->Rights.ModeStr)));
  760. }
  761. if (RProperties->Valid.Contains(vpGroup))
  762. {
  763. LogEvent(FORMAT(" - group: \"%s\"", (RProperties->Group)));
  764. }
  765. if (RProperties->Valid.Contains(vpOwner))
  766. {
  767. LogEvent(FORMAT(" - owner: \"%s\"", (RProperties->Owner)));
  768. }
  769. }
  770. if (File) FileModified(File);
  771. DoChangeFileProperties(FileName, File, RProperties);
  772. ReactOnCommand(fsChangeProperties);
  773. }
  774. //---------------------------------------------------------------------------
  775. void __fastcall TTerminal::DoChangeFileProperties(const AnsiString FileName,
  776. const TRemoteFile * File, const TRemoteProperties * Properties)
  777. {
  778. try
  779. {
  780. assert(FFileSystem);
  781. FFileSystem->ChangeFileProperties(FileName, File, Properties);
  782. }
  783. catch(Exception & E)
  784. {
  785. COMMAND_ERROR_ARI
  786. (
  787. FMTLOAD(CHANGE_PROPERTIES_ERROR, (FileName)),
  788. DoChangeFileProperties(FileName, File, Properties)
  789. );
  790. }
  791. }
  792. //---------------------------------------------------------------------------
  793. void __fastcall TTerminal::ChangeFilesProperties(TStrings * FileList,
  794. const TRemoteProperties * Properties)
  795. {
  796. ProcessFiles(FileList, foSetProperties, ChangeFileProperties, (void *)Properties);
  797. }
  798. //---------------------------------------------------------------------------
  799. void __fastcall TTerminal::RenameFile(const AnsiString FileName,
  800. const AnsiString NewName)
  801. {
  802. LogEvent(FORMAT("Renaming file \"%s\" to \"%s\".", (FileName, NewName)));
  803. DoRenameFile(FileName, NewName);
  804. ReactOnCommand(fsRenameFile);
  805. }
  806. //---------------------------------------------------------------------------
  807. void __fastcall TTerminal::RenameFile(const TRemoteFile * File,
  808. const AnsiString NewName, bool CheckExistence)
  809. {
  810. assert(File && File->Directory == FFiles);
  811. bool Proceed = true;
  812. // if filename doesn't contain path, we check for existence of file
  813. if ((File->FileName != NewName) && CheckExistence &&
  814. Configuration->ConfirmOverwriting &&
  815. UnixComparePaths(CurrentDirectory, FFiles->Directory))
  816. {
  817. TRemoteFile * DuplicateFile = FFiles->FindFile(NewName);
  818. if (DuplicateFile)
  819. {
  820. AnsiString QuestionFmt;
  821. if (DuplicateFile->IsDirectory) QuestionFmt = LoadStr(DIRECTORY_OVERWRITE);
  822. else QuestionFmt = LoadStr(FILE_OVERWRITE);
  823. int Result;
  824. Result = DoQueryUser(FORMAT(QuestionFmt, (NewName)),
  825. qaYes | qaNo, qpNeverAskAgainCheck);
  826. if (Result == qaNeverAskAgain)
  827. {
  828. Proceed = true;
  829. Configuration->ConfirmOverwriting = false;
  830. }
  831. else
  832. {
  833. Proceed = (Result == qaYes);
  834. }
  835. }
  836. }
  837. if (Proceed)
  838. {
  839. FileModified(File);
  840. RenameFile(File->FileName, NewName);
  841. }
  842. }
  843. //---------------------------------------------------------------------------
  844. void __fastcall TTerminal::DoRenameFile(const AnsiString FileName,
  845. const AnsiString NewName)
  846. {
  847. try
  848. {
  849. assert(FFileSystem);
  850. FFileSystem->RenameFile(FileName, NewName);
  851. }
  852. catch(Exception & E)
  853. {
  854. COMMAND_ERROR_ARI
  855. (
  856. FMTLOAD(RENAME_FILE_ERROR, (FileName, NewName)),
  857. DoRenameFile(FileName, NewName)
  858. );
  859. }
  860. }
  861. //---------------------------------------------------------------------------
  862. void __fastcall TTerminal::CreateDirectory(const AnsiString DirName,
  863. const TRemoteProperties * Properties)
  864. {
  865. assert(FFileSystem);
  866. EnsureNonExistence(DirName);
  867. if (SessionData->CacheDirectories)
  868. {
  869. FDirectoryCache->ClearFileList(CurrentDirectory, false);
  870. }
  871. LogEvent(FORMAT("Creating directory \"%s\".", (DirName)));
  872. DoCreateDirectory(DirName, Properties);
  873. ReactOnCommand(fsCreateDirectory);
  874. }
  875. //---------------------------------------------------------------------------
  876. void __fastcall TTerminal::DoCreateDirectory(const AnsiString DirName,
  877. const TRemoteProperties * Properties)
  878. {
  879. try
  880. {
  881. assert(FFileSystem);
  882. FFileSystem->CreateDirectory(DirName, Properties);
  883. }
  884. catch(Exception & E)
  885. {
  886. COMMAND_ERROR_ARI
  887. (
  888. FMTLOAD(CREATE_DIR_ERROR, (DirName)),
  889. DoCreateDirectory(DirName, Properties)
  890. );
  891. }
  892. }
  893. //---------------------------------------------------------------------------
  894. void __fastcall TTerminal::CreateLink(const AnsiString FileName,
  895. const AnsiString PointTo, bool Symbolic)
  896. {
  897. assert(FFileSystem);
  898. EnsureNonExistence(FileName);
  899. if (SessionData->CacheDirectories)
  900. {
  901. FDirectoryCache->ClearFileList(CurrentDirectory, false);
  902. }
  903. LogEvent(FORMAT("Creating link \"%s\" to \"%s\" (symbolic: %s).",
  904. (FileName, PointTo, BooleanToEngStr(Symbolic))));
  905. DoCreateLink(FileName, PointTo, Symbolic);
  906. ReactOnCommand(fsCreateDirectory);
  907. }
  908. //---------------------------------------------------------------------------
  909. void __fastcall TTerminal::DoCreateLink(const AnsiString FileName,
  910. const AnsiString PointTo, bool Symbolic)
  911. {
  912. try
  913. {
  914. assert(FFileSystem);
  915. FFileSystem->CreateLink(FileName, PointTo, Symbolic);
  916. }
  917. catch(Exception & E)
  918. {
  919. COMMAND_ERROR_ARI
  920. (
  921. FMTLOAD(CREATE_LINK_ERROR, (FileName)),
  922. DoCreateLink(FileName, PointTo, Symbolic);
  923. );
  924. }
  925. }
  926. //---------------------------------------------------------------------------
  927. void __fastcall TTerminal::HomeDirectory()
  928. {
  929. assert(FFileSystem);
  930. try
  931. {
  932. LogEvent("Changing directory to home directory.");
  933. FFileSystem->HomeDirectory();
  934. ReactOnCommand(fsHomeDirectory);
  935. }
  936. catch (Exception &E)
  937. {
  938. CommandError(&E, LoadStr(CHANGE_HOMEDIR_ERROR));
  939. }
  940. }
  941. //---------------------------------------------------------------------------
  942. void __fastcall TTerminal::ChangeDirectory(const AnsiString Directory)
  943. {
  944. assert(FFileSystem);
  945. try
  946. {
  947. LogEvent(FORMAT("Changing directory to \"%s\".", (Directory)));
  948. FFileSystem->ChangeDirectory(Directory);
  949. ReactOnCommand(fsChangeDirectory);
  950. }
  951. catch (Exception &E)
  952. {
  953. CommandError(&E, FMTLOAD(CHANGE_DIR_ERROR, (Directory)));
  954. }
  955. }
  956. //---------------------------------------------------------------------------
  957. void __fastcall TTerminal::LookupUserGroups()
  958. {
  959. assert(FFileSystem);
  960. assert(IsCapable[fcUserGroupListing]);
  961. try
  962. {
  963. FUserGroupsLookedup = true;
  964. LogEvent("Looking up current user groups.");
  965. FFileSystem->LookupUserGroups();
  966. ReactOnCommand(fsLookupUserGroups);
  967. if (IsLogging())
  968. {
  969. LogEvent("Following groups found:");
  970. for (int Index = 0; Index < FUserGroups->Count; Index++)
  971. {
  972. LogEvent(AnsiString(" ") + FUserGroups->Strings[Index]);
  973. }
  974. }
  975. }
  976. catch (Exception &E)
  977. {
  978. CommandError(&E, LoadStr(LOOKUP_GROUPS_ERROR));
  979. }
  980. }
  981. //---------------------------------------------------------------------------
  982. void __fastcall TTerminal::AnyCommand(const AnsiString Command)
  983. {
  984. assert(FFileSystem);
  985. try
  986. {
  987. DirectoryModified(CurrentDirectory, false);
  988. LogEvent("Executing used defined command.");
  989. FFileSystem->AnyCommand(Command);
  990. ReactOnCommand(fsAnyCommand);
  991. }
  992. catch (Exception &E)
  993. {
  994. if (ExceptionOnFail || (E.InheritsFrom(__classid(EFatal)))) throw;
  995. else ShowExtendedException(&E, this);
  996. }
  997. }
  998. //---------------------------------------------------------------------------
  999. void __fastcall TTerminal::OpenLocalFile(const AnsiString FileName,
  1000. int Access, int * AAttrs, HANDLE * AHandle, unsigned long * ACTime,
  1001. unsigned long * AMTime, unsigned long * AATime, __int64 * ASize)
  1002. {
  1003. TTerminal * FTerminal = this; //required by FILE_OPERATION_LOOP macro
  1004. int Attrs = 0;
  1005. HANDLE Handle = 0;
  1006. FILE_OPERATION_LOOP (FileName, FMTLOAD(FILE_NOT_EXISTS, (FileName)),
  1007. Attrs = FileGetAttr(FileName);
  1008. if (Attrs == -1) EXCEPTION;
  1009. )
  1010. if ((Attrs & faDirectory) == 0)
  1011. {
  1012. FILE_OPERATION_LOOP (FileName, FMTLOAD(OPENFILE_ERROR, (FileName)),
  1013. Handle = CreateFile(FileName.c_str(), Access,
  1014. Access == GENERIC_READ ? FILE_SHARE_READ : 0,
  1015. NULL, OPEN_EXISTING, 0, 0);
  1016. if (Handle == INVALID_HANDLE_VALUE)
  1017. {
  1018. Handle = 0;
  1019. EXCEPTION;
  1020. }
  1021. );
  1022. try
  1023. {
  1024. if (AATime || AMTime)
  1025. {
  1026. // Get last file access and modification time
  1027. FILE_OPERATION_LOOP (FileName, FMTLOAD(CANT_GET_ATTRS, (FileName)),
  1028. FILETIME ATime;
  1029. FILETIME MTime;
  1030. FILETIME CTime;
  1031. if (!GetFileTime(Handle, &CTime, &ATime, &MTime)) EXCEPTION;
  1032. if (ACTime) TIME_WIN_TO_POSIX(CTime, *ACTime);
  1033. if (AATime) TIME_WIN_TO_POSIX(ATime, *AATime);
  1034. if (AMTime) TIME_WIN_TO_POSIX(MTime, *AMTime);
  1035. );
  1036. }
  1037. if (ASize)
  1038. {
  1039. // Get file size
  1040. FILE_OPERATION_LOOP (FileName, FMTLOAD(CANT_GET_ATTRS, (FileName)),
  1041. unsigned long LSize;
  1042. unsigned long HSize;
  1043. LSize = GetFileSize(Handle, &HSize);
  1044. if ((LSize == 0xFFFFFFFF) && (GetLastError() != NO_ERROR)) EXCEPTION;
  1045. *ASize = (__int64(HSize) << 32) + LSize;
  1046. );
  1047. }
  1048. }
  1049. catch(...)
  1050. {
  1051. CloseHandle(Handle);
  1052. throw;
  1053. }
  1054. }
  1055. if (AAttrs) *AAttrs = Attrs;
  1056. if (AHandle) *AHandle = Handle;
  1057. }
  1058. //---------------------------------------------------------------------------
  1059. void __fastcall TTerminal::CopyToRemote(TStrings * FilesToCopy,
  1060. const AnsiString TargetDir, const TCopyParamType * CopyParam, int Params)
  1061. {
  1062. assert(FFileSystem);
  1063. assert(FilesToCopy);
  1064. bool DisconnectWhenComplete = false;
  1065. try
  1066. {
  1067. TFileOperationProgressType OperationProgress(FOnProgress, FOnFinished);
  1068. OperationProgress.Start((Params & cpDelete ? foMove : foCopy), osLocal,
  1069. FilesToCopy->Count, Params & cpDragDrop, TargetDir);
  1070. FOperationProgress = &OperationProgress;
  1071. try
  1072. {
  1073. AnsiString UnlockedTargetDir = TranslateLockedPath(TargetDir, false);
  1074. BeginTransaction();
  1075. try
  1076. {
  1077. if (IsLogging())
  1078. {
  1079. LogEvent(FORMAT("Copying %d files/directories to remote directory "
  1080. "\"%s\"", (FilesToCopy->Count, TargetDir)));
  1081. LogEvent(CopyParam->LogStr);
  1082. }
  1083. FFileSystem->CopyToRemote(FilesToCopy, UnlockedTargetDir,
  1084. CopyParam, Params, &OperationProgress, DisconnectWhenComplete);
  1085. }
  1086. __finally
  1087. {
  1088. if (Active)
  1089. {
  1090. ReactOnCommand(fsCopyToRemote);
  1091. EndTransaction();
  1092. }
  1093. }
  1094. }
  1095. __finally
  1096. {
  1097. OperationProgress.Stop();
  1098. FOperationProgress = NULL;
  1099. }
  1100. }
  1101. catch (Exception &E)
  1102. {
  1103. CommandError(&E, LoadStr(TOREMOTE_COPY_ERROR));
  1104. DisconnectWhenComplete = false;
  1105. }
  1106. if (DisconnectWhenComplete) CloseOnCompletion();
  1107. }
  1108. //---------------------------------------------------------------------------
  1109. void __fastcall TTerminal::CopyToLocal(TStrings * FilesToCopy,
  1110. const AnsiString TargetDir, const TCopyParamType * CopyParam, int Params)
  1111. {
  1112. assert(FFileSystem);
  1113. // see scp.c: sink(), tolocal()
  1114. bool OwnsFileList = (FilesToCopy == NULL);
  1115. bool DisconnectWhenComplete = false;
  1116. try
  1117. {
  1118. if (OwnsFileList)
  1119. {
  1120. FilesToCopy = new TStringList();
  1121. FilesToCopy->Assign(Files->SelectedFiles);
  1122. }
  1123. BeginTransaction();
  1124. try
  1125. {
  1126. TFileOperationProgressType OperationProgress(FOnProgress, FOnFinished);
  1127. OperationProgress.Start((Params & cpDelete ? foMove : foCopy), osRemote,
  1128. FilesToCopy->Count, Params & cpDragDrop, TargetDir);
  1129. FOperationProgress = &OperationProgress;
  1130. try
  1131. {
  1132. try
  1133. {
  1134. try
  1135. {
  1136. FFileSystem->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params,
  1137. &OperationProgress, DisconnectWhenComplete);
  1138. }
  1139. __finally
  1140. {
  1141. if (Active)
  1142. {
  1143. ReactOnCommand(fsCopyToLocal);
  1144. }
  1145. }
  1146. }
  1147. catch (Exception &E)
  1148. {
  1149. CommandError(&E, LoadStr(TOLOCAL_COPY_ERROR));
  1150. DisconnectWhenComplete = false;
  1151. }
  1152. }
  1153. __finally
  1154. {
  1155. FOperationProgress = NULL;
  1156. OperationProgress.Stop();
  1157. }
  1158. }
  1159. __finally
  1160. {
  1161. // If session is still active (no fatal error) we reload directory
  1162. // by calling EndTransaction
  1163. EndTransaction();
  1164. }
  1165. }
  1166. __finally
  1167. {
  1168. if (OwnsFileList) delete FilesToCopy;
  1169. }
  1170. if (DisconnectWhenComplete) CloseOnCompletion();
  1171. }
  1172. //---------------------------------------------------------------------------
  1173. __fastcall TTerminalList::TTerminalList(TConfiguration * AConfiguration) :
  1174. TObjectList()
  1175. {
  1176. assert(AConfiguration);
  1177. FConfiguration = AConfiguration;
  1178. }
  1179. //---------------------------------------------------------------------------
  1180. __fastcall TTerminalList::~TTerminalList()
  1181. {
  1182. assert(Count == 0);
  1183. }
  1184. //---------------------------------------------------------------------------
  1185. TTerminal * __fastcall TTerminalList::NewTerminal(TSessionData * Data)
  1186. {
  1187. TTerminal * Terminal = new TTerminal();
  1188. try
  1189. {
  1190. Terminal->Configuration = FConfiguration;
  1191. Terminal->SessionData = Data;
  1192. Add(Terminal);
  1193. }
  1194. catch(...)
  1195. {
  1196. delete Terminal;
  1197. throw;
  1198. }
  1199. return Terminal;
  1200. }
  1201. //---------------------------------------------------------------------------
  1202. void __fastcall TTerminalList::FreeTerminal(TTerminal * Terminal)
  1203. {
  1204. assert(IndexOf(Terminal) >= 0);
  1205. Remove(Terminal);
  1206. }
  1207. //---------------------------------------------------------------------------
  1208. void __fastcall TTerminalList::FreeAndNullTerminal(TTerminal * & Terminal)
  1209. {
  1210. TTerminal * T = Terminal;
  1211. Terminal = NULL;
  1212. FreeTerminal(T);
  1213. }
  1214. //---------------------------------------------------------------------------
  1215. TTerminal * __fastcall TTerminalList::GetTerminal(int Index)
  1216. {
  1217. return dynamic_cast<TTerminal *>(Items[Index]);
  1218. }
  1219. //---------------------------------------------------------------------------
  1220. void __fastcall TTerminalList::Idle()
  1221. {
  1222. TTerminal * Terminal;
  1223. for (int i = 0; i < Count; i++)
  1224. {
  1225. Terminal = Terminals[i];
  1226. if (Terminal->Status == sshReady)
  1227. {
  1228. Terminal->Idle();
  1229. }
  1230. }
  1231. }