Terminal.cpp 125 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154
  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 "PuttyTools.h"
  9. #include "Exceptions.h"
  10. #include "FileBuffer.h"
  11. #include "Interface.h"
  12. #include "RemoteFiles.h"
  13. #include "SecureShell.h"
  14. #include "ScpFileSystem.h"
  15. #include "SftpFileSystem.h"
  16. #ifndef NO_FILEZILLA
  17. #include "FtpFileSystem.h"
  18. #endif
  19. #include "TextsCore.h"
  20. #include "HelpCore.h"
  21. #include "Security.h"
  22. #include "CoreMain.h"
  23. #include "Queue.h"
  24. //---------------------------------------------------------------------------
  25. #pragma package(smart_init)
  26. //---------------------------------------------------------------------------
  27. #define SSH_ERROR(x) throw ESsh(NULL, x)
  28. #define SSH_FATAL_ERROR_EXT(E, x) throw ESshFatal(E, x)
  29. #define SSH_FATAL_ERROR(x) SSH_FATAL_ERROR_EXT(NULL, x)
  30. //---------------------------------------------------------------------------
  31. #define COMMAND_ERROR_ARI(MESSAGE, REPEAT) \
  32. { \
  33. int Result = CommandError(&E, MESSAGE, qaRetry | qaSkip | qaAbort); \
  34. switch (Result) { \
  35. case qaRetry: { REPEAT; } break; \
  36. case qaAbort: Abort(); \
  37. } \
  38. }
  39. #define FILE_OPERATION_LOOP_EX(ALLOW_SKIP, MESSAGE, OPERATION) \
  40. FILE_OPERATION_LOOP_CUSTOM(this, ALLOW_SKIP, MESSAGE, OPERATION)
  41. //---------------------------------------------------------------------------
  42. struct TMoveFileParams
  43. {
  44. AnsiString Target;
  45. AnsiString FileMask;
  46. };
  47. //---------------------------------------------------------------------------
  48. TCalculateSizeStats::TCalculateSizeStats()
  49. {
  50. memset(this, 0, sizeof(*this));
  51. }
  52. //---------------------------------------------------------------------------
  53. TSynchronizeOptions::TSynchronizeOptions()
  54. {
  55. memset(this, 0, sizeof(*this));
  56. }
  57. //---------------------------------------------------------------------------
  58. TSynchronizeOptions::~TSynchronizeOptions()
  59. {
  60. delete Filter;
  61. }
  62. //---------------------------------------------------------------------------
  63. TSpaceAvailable::TSpaceAvailable()
  64. {
  65. memset(this, 0, sizeof(*this));
  66. }
  67. //---------------------------------------------------------------------------
  68. TOverwriteFileParams::TOverwriteFileParams()
  69. {
  70. SourceSize = 0;
  71. DestSize = 0;
  72. SourcePrecision = mfFull;
  73. DestPrecision = mfFull;
  74. }
  75. //---------------------------------------------------------------------------
  76. //---------------------------------------------------------------------------
  77. TSynchronizeChecklist::TItem::TItem() :
  78. Action(saNone), IsDirectory(false), FRemoteFile(NULL), Checked(true), ImageIndex(-1)
  79. {
  80. Local.ModificationFmt = mfFull;
  81. Local.Modification = 0;
  82. Local.Size = 0;
  83. Remote.ModificationFmt = mfFull;
  84. Remote.Modification = 0;
  85. Remote.Size = 0;
  86. }
  87. //---------------------------------------------------------------------------
  88. TSynchronizeChecklist::TItem::~TItem()
  89. {
  90. delete FRemoteFile;
  91. }
  92. //---------------------------------------------------------------------------
  93. //---------------------------------------------------------------------------
  94. TSynchronizeChecklist::TSynchronizeChecklist() :
  95. FList(new TList())
  96. {
  97. }
  98. //---------------------------------------------------------------------------
  99. TSynchronizeChecklist::~TSynchronizeChecklist()
  100. {
  101. for (int Index = 0; Index < FList->Count; Index++)
  102. {
  103. delete static_cast<TItem *>(FList->Items[Index]);
  104. }
  105. delete FList;
  106. }
  107. //---------------------------------------------------------------------------
  108. void TSynchronizeChecklist::Add(TItem * Item)
  109. {
  110. FList->Add(Item);
  111. }
  112. //---------------------------------------------------------------------------
  113. int __fastcall TSynchronizeChecklist::Compare(void * AItem1, void * AItem2)
  114. {
  115. TItem * Item1 = static_cast<TItem *>(AItem1);
  116. TItem * Item2 = static_cast<TItem *>(AItem2);
  117. int Result;
  118. if (!Item1->Local.Directory.IsEmpty())
  119. {
  120. Result = CompareText(Item1->Local.Directory, Item2->Local.Directory);
  121. }
  122. else
  123. {
  124. assert(!Item1->Remote.Directory.IsEmpty());
  125. Result = CompareText(Item1->Remote.Directory, Item2->Remote.Directory);
  126. }
  127. if (Result == 0)
  128. {
  129. Result = CompareText(Item1->FileName, Item2->FileName);
  130. }
  131. return Result;
  132. }
  133. //---------------------------------------------------------------------------
  134. void TSynchronizeChecklist::Sort()
  135. {
  136. FList->Sort(Compare);
  137. }
  138. //---------------------------------------------------------------------------
  139. int TSynchronizeChecklist::GetCount() const
  140. {
  141. return FList->Count;
  142. }
  143. //---------------------------------------------------------------------------
  144. const TSynchronizeChecklist::TItem * TSynchronizeChecklist::GetItem(int Index) const
  145. {
  146. return static_cast<TItem *>(FList->Items[Index]);
  147. }
  148. //---------------------------------------------------------------------------
  149. //---------------------------------------------------------------------------
  150. class TTunnelThread : public TSimpleThread
  151. {
  152. public:
  153. __fastcall TTunnelThread(TSecureShell * SecureShell);
  154. virtual __fastcall ~TTunnelThread();
  155. virtual void __fastcall Terminate();
  156. protected:
  157. virtual void __fastcall Execute();
  158. private:
  159. TSecureShell * FSecureShell;
  160. bool FTerminated;
  161. };
  162. //---------------------------------------------------------------------------
  163. __fastcall TTunnelThread::TTunnelThread(TSecureShell * SecureShell) :
  164. FSecureShell(SecureShell),
  165. FTerminated(false)
  166. {
  167. Start();
  168. }
  169. //---------------------------------------------------------------------------
  170. __fastcall TTunnelThread::~TTunnelThread()
  171. {
  172. // close before the class's virtual functions (Terminate particularly) are lost
  173. Close();
  174. }
  175. //---------------------------------------------------------------------------
  176. void __fastcall TTunnelThread::Terminate()
  177. {
  178. FTerminated = true;
  179. }
  180. //---------------------------------------------------------------------------
  181. void __fastcall TTunnelThread::Execute()
  182. {
  183. try
  184. {
  185. while (!FTerminated)
  186. {
  187. FSecureShell->Idle(250);
  188. }
  189. }
  190. catch(...)
  191. {
  192. if (FSecureShell->Active)
  193. {
  194. FSecureShell->Close();
  195. }
  196. throw;
  197. }
  198. }
  199. //---------------------------------------------------------------------------
  200. //---------------------------------------------------------------------------
  201. class TTunnelUI : public TSessionUI
  202. {
  203. public:
  204. __fastcall TTunnelUI(TTerminal * Terminal);
  205. virtual void __fastcall Information(const AnsiString & Str, bool Status);
  206. virtual int __fastcall QueryUser(const AnsiString Query,
  207. TStrings * MoreMessages, int Answers, const TQueryParams * Params,
  208. TQueryType QueryType);
  209. virtual int __fastcall QueryUserException(const AnsiString Query,
  210. Exception * E, int Answers, const TQueryParams * Params,
  211. TQueryType QueryType);
  212. virtual bool __fastcall PromptUser(TSessionData * Data, AnsiString Prompt,
  213. TPromptKind Kind, AnsiString & Response);
  214. virtual void __fastcall DisplayBanner(const AnsiString & Banner);
  215. virtual void __fastcall ShowExtendedException(Exception * E);
  216. virtual void __fastcall Closed();
  217. private:
  218. TTerminal * FTerminal;
  219. unsigned int FTerminalThread;
  220. };
  221. //---------------------------------------------------------------------------
  222. __fastcall TTunnelUI::TTunnelUI(TTerminal * Terminal)
  223. {
  224. FTerminal = Terminal;
  225. FTerminalThread = GetCurrentThreadId();
  226. }
  227. //---------------------------------------------------------------------------
  228. void __fastcall TTunnelUI::Information(const AnsiString & Str, bool Status)
  229. {
  230. if (GetCurrentThreadId() == FTerminalThread)
  231. {
  232. FTerminal->Information(Str, Status);
  233. }
  234. }
  235. //---------------------------------------------------------------------------
  236. int __fastcall TTunnelUI::QueryUser(const AnsiString Query,
  237. TStrings * MoreMessages, int Answers, const TQueryParams * Params,
  238. TQueryType QueryType)
  239. {
  240. int Result;
  241. if (GetCurrentThreadId() == FTerminalThread)
  242. {
  243. Result = FTerminal->QueryUser(Query, MoreMessages, Answers, Params, QueryType);
  244. }
  245. else
  246. {
  247. Result = AbortAnswer(Answers);
  248. }
  249. return Result;
  250. }
  251. //---------------------------------------------------------------------------
  252. int __fastcall TTunnelUI::QueryUserException(const AnsiString Query,
  253. Exception * E, int Answers, const TQueryParams * Params,
  254. TQueryType QueryType)
  255. {
  256. int Result;
  257. if (GetCurrentThreadId() == FTerminalThread)
  258. {
  259. Result = FTerminal->QueryUserException(Query, E, Answers, Params, QueryType);
  260. }
  261. else
  262. {
  263. Result = AbortAnswer(Answers);
  264. }
  265. return Result;
  266. }
  267. //---------------------------------------------------------------------------
  268. bool __fastcall TTunnelUI::PromptUser(TSessionData * Data, AnsiString Prompt,
  269. TPromptKind Kind, AnsiString & Response)
  270. {
  271. bool Result;
  272. if (GetCurrentThreadId() == FTerminalThread)
  273. {
  274. Result = FTerminal->PromptUser(Data, Prompt, Kind, Response);
  275. }
  276. else
  277. {
  278. Result = false;
  279. }
  280. return Result;
  281. }
  282. //---------------------------------------------------------------------------
  283. void __fastcall TTunnelUI::DisplayBanner(const AnsiString & Banner)
  284. {
  285. if (GetCurrentThreadId() == FTerminalThread)
  286. {
  287. FTerminal->DisplayBanner(Banner);
  288. }
  289. }
  290. //---------------------------------------------------------------------------
  291. void __fastcall TTunnelUI::ShowExtendedException(Exception * E)
  292. {
  293. if (GetCurrentThreadId() == FTerminalThread)
  294. {
  295. FTerminal->ShowExtendedException(E);
  296. }
  297. }
  298. //---------------------------------------------------------------------------
  299. void __fastcall TTunnelUI::Closed()
  300. {
  301. // noop
  302. }
  303. //---------------------------------------------------------------------------
  304. //---------------------------------------------------------------------------
  305. std::set<int> TTerminal::FTunnelLocalPorts;
  306. TCriticalSection TTerminal::FSection;
  307. //---------------------------------------------------------------------------
  308. __fastcall TTerminal::TTerminal(TSessionData * SessionData,
  309. TConfiguration * Configuration)
  310. {
  311. FConfiguration = Configuration;
  312. FSessionData = new TSessionData("");
  313. FSessionData->Assign(SessionData);
  314. FLog = new TSessionLog(this, FSessionData, Configuration);
  315. FFiles = new TRemoteDirectory(this);
  316. FExceptionOnFail = 0;
  317. FInTransaction = 0;
  318. FReadCurrentDirectoryPending = false;
  319. FReadDirectoryPending = false;
  320. FUsersGroupsLookedup = False;
  321. FTunnelLocalPortNumber = 0;
  322. FGroups = new TUsersGroupsList();
  323. FUsers = new TUsersGroupsList();
  324. FFileSystem = NULL;
  325. FSecureShell = NULL;
  326. FOnProgress = NULL;
  327. FOnFinished = NULL;
  328. FOnDeleteLocalFile = NULL;
  329. FOnReadDirectoryProgress = NULL;
  330. FOnQueryUser = NULL;
  331. FOnPromptUser = NULL;
  332. FOnDisplayBanner = NULL;
  333. FOnShowExtendedException = NULL;
  334. FOnInformation = NULL;
  335. FOnClose = NULL;
  336. FUseBusyCursor = True;
  337. FLockDirectory = "";
  338. FDirectoryCache = new TRemoteDirectoryCache();
  339. FDirectoryChangesCache = NULL;
  340. FFSProtocol = cfsUnknown;
  341. FCommandSession = NULL;
  342. FAutoReadDirectory = true;
  343. FReadingCurrentDirectory = false;
  344. FStatus = ssClosed;
  345. FTunnelThread = NULL;
  346. FTunnel = NULL;
  347. FTunnelData = NULL;
  348. FTunnelLog = NULL;
  349. FTunnelUI = NULL;
  350. }
  351. //---------------------------------------------------------------------------
  352. __fastcall TTerminal::~TTerminal()
  353. {
  354. if (Active)
  355. {
  356. Close();
  357. }
  358. assert(FTunnel == NULL);
  359. SAFE_DESTROY(FCommandSession);
  360. if (SessionData->CacheDirectoryChanges && SessionData->PreserveDirectoryChanges &&
  361. (FDirectoryChangesCache != NULL))
  362. {
  363. Configuration->SaveDirectoryChangesCache(SessionData->SessionKey,
  364. FDirectoryChangesCache);
  365. }
  366. SAFE_DESTROY_EX(TCustomFileSystem, FFileSystem);
  367. SAFE_DESTROY_EX(TSessionLog, FLog);
  368. delete FFiles;
  369. delete FGroups;
  370. delete FUsers;
  371. delete FDirectoryCache;
  372. delete FDirectoryChangesCache;
  373. SAFE_DESTROY(FSessionData);
  374. }
  375. //---------------------------------------------------------------------------
  376. void __fastcall TTerminal::Idle()
  377. {
  378. if (Configuration->LogProtocol >= 1)
  379. {
  380. LogEvent("Session upkeep");
  381. }
  382. assert(FFileSystem != NULL);
  383. FFileSystem->Idle();
  384. if (CommandSessionOpened)
  385. {
  386. try
  387. {
  388. FCommandSession->Idle();
  389. }
  390. catch(Exception & E)
  391. {
  392. // If the secondary session is dropped, ignore the error and let
  393. // it be reconnected when needed.
  394. // BTW, non-fatal error can hardly happen here, that's why
  395. // it is displayed, because it can be useful to know.
  396. if (FCommandSession->Active)
  397. {
  398. FCommandSession->ShowExtendedException(&E);
  399. }
  400. }
  401. }
  402. }
  403. //---------------------------------------------------------------------------
  404. bool __fastcall TTerminal::IsAbsolutePath(const AnsiString Path)
  405. {
  406. return !Path.IsEmpty() && Path[1] == '/';
  407. }
  408. //---------------------------------------------------------------------------
  409. AnsiString __fastcall TTerminal::ExpandFileName(AnsiString Path,
  410. const AnsiString BasePath)
  411. {
  412. Path = UnixExcludeTrailingBackslash(Path);
  413. if (!IsAbsolutePath(Path) && !BasePath.IsEmpty())
  414. {
  415. // TODO: Handle more complicated cases like "../../xxx"
  416. if (Path == "..")
  417. {
  418. Path = UnixExcludeTrailingBackslash(UnixExtractFilePath(
  419. UnixExcludeTrailingBackslash(BasePath)));
  420. }
  421. else
  422. {
  423. Path = UnixIncludeTrailingBackslash(BasePath) + Path;
  424. }
  425. }
  426. return Path;
  427. }
  428. //---------------------------------------------------------------------------
  429. bool __fastcall TTerminal::GetActive()
  430. {
  431. return (FFileSystem != NULL) && FFileSystem->GetActive();
  432. }
  433. //---------------------------------------------------------------------------
  434. void __fastcall TTerminal::Close()
  435. {
  436. FFileSystem->Close();
  437. if (CommandSessionOpened)
  438. {
  439. FCommandSession->Close();
  440. }
  441. }
  442. //---------------------------------------------------------------------------
  443. void __fastcall TTerminal::ResetConnection()
  444. {
  445. FAnyInformation = false;
  446. // used to be called from Reopen(), why?
  447. FTunnelError = "";
  448. if (FDirectoryChangesCache != NULL)
  449. {
  450. delete FDirectoryChangesCache;
  451. FDirectoryChangesCache = NULL;
  452. }
  453. }
  454. //---------------------------------------------------------------------------
  455. void __fastcall TTerminal::Open()
  456. {
  457. try
  458. {
  459. try
  460. {
  461. try
  462. {
  463. ResetConnection();
  464. FStatus = ssOpening;
  465. try
  466. {
  467. if (FFileSystem == NULL)
  468. {
  469. Log->AddStartupInfo();
  470. }
  471. assert(FTunnel == NULL);
  472. if (FSessionData->Tunnel)
  473. {
  474. DoInformation(LoadStr(OPEN_TUNNEL), true);
  475. LogEvent("Opening tunnel.");
  476. OpenTunnel();
  477. Log->AddSeparator();
  478. FSessionData->ConfigureTunnel(FTunnelLocalPortNumber);
  479. DoInformation(LoadStr(USING_TUNNEL), false);
  480. LogEvent(FORMAT("Connecting via tunnel interface %s:%d.",
  481. (FSessionData->HostName, FSessionData->PortNumber)));
  482. }
  483. else
  484. {
  485. assert(FTunnelLocalPortNumber == 0);
  486. }
  487. if (FFileSystem == NULL)
  488. {
  489. if (SessionData->FSProtocol == fsFTP)
  490. {
  491. #ifdef NO_FILEZILLA
  492. LogEvent("FTP protocol is not supported by this build.");
  493. FatalError(NULL, LoadStr(FTP_UNSUPPORTED));
  494. #else
  495. FFSProtocol = cfsFTP;
  496. FFileSystem = new TFTPFileSystem(this);
  497. FFileSystem->Open();
  498. Log->AddSeparator();
  499. LogEvent("Using FTP protocol.");
  500. #endif
  501. }
  502. else
  503. {
  504. assert(FSecureShell == NULL);
  505. try
  506. {
  507. FSecureShell = new TSecureShell(this, FSessionData, Log, Configuration);
  508. try
  509. {
  510. FSecureShell->Open();
  511. }
  512. catch(Exception & E)
  513. {
  514. assert(!FSecureShell->Active);
  515. if (!FSecureShell->Active && !FTunnelError.IsEmpty())
  516. {
  517. // the only case where we expect this to happen
  518. assert(E.Message == LoadStr(UNEXPECTED_CLOSE_ERROR));
  519. FatalError(&E, FMTLOAD(TUNNEL_ERROR, (FTunnelError)));
  520. }
  521. else
  522. {
  523. throw;
  524. }
  525. }
  526. Log->AddSeparator();
  527. if ((SessionData->FSProtocol == fsSCPonly) ||
  528. (SessionData->FSProtocol == fsSFTP && FSecureShell->SshFallbackCmd()))
  529. {
  530. FFSProtocol = cfsSCP;
  531. FFileSystem = new TSCPFileSystem(this, FSecureShell);
  532. FSecureShell = NULL; // ownership passed
  533. LogEvent("Using SCP protocol.");
  534. }
  535. else
  536. {
  537. FFSProtocol = cfsSFTP;
  538. FFileSystem = new TSFTPFileSystem(this, FSecureShell);
  539. FSecureShell = NULL; // ownership passed
  540. LogEvent("Using SFTP protocol.");
  541. }
  542. }
  543. __finally
  544. {
  545. delete FSecureShell;
  546. FSecureShell = NULL;
  547. }
  548. }
  549. }
  550. else
  551. {
  552. FFileSystem->Open();
  553. }
  554. }
  555. __finally
  556. {
  557. if (FSessionData->Tunnel)
  558. {
  559. FSessionData->RollbackTunnel();
  560. }
  561. }
  562. if (SessionData->CacheDirectoryChanges)
  563. {
  564. assert(FDirectoryChangesCache == NULL);
  565. FDirectoryChangesCache = new TRemoteDirectoryChangesCache();
  566. if (SessionData->PreserveDirectoryChanges)
  567. {
  568. Configuration->LoadDirectoryChangesCache(SessionData->SessionKey,
  569. FDirectoryChangesCache);
  570. }
  571. }
  572. DoStartup();
  573. DoInformation(LoadStr(STATUS_READY), true);
  574. FStatus = ssOpened;
  575. }
  576. catch(...)
  577. {
  578. // rollback
  579. if (FDirectoryChangesCache != NULL)
  580. {
  581. delete FDirectoryChangesCache;
  582. FDirectoryChangesCache = NULL;
  583. }
  584. throw;
  585. }
  586. }
  587. __finally
  588. {
  589. // Prevent calling Information with active=false unless there was at least
  590. // one call with active=true
  591. if (FAnyInformation)
  592. {
  593. DoInformation("", true, false);
  594. }
  595. }
  596. }
  597. catch(EFatal &)
  598. {
  599. throw;
  600. }
  601. catch(Exception & E)
  602. {
  603. // any exception while opening session is fatal
  604. FatalError(&E, "");
  605. }
  606. }
  607. //---------------------------------------------------------------------------
  608. void __fastcall TTerminal::OpenTunnel()
  609. {
  610. assert(FTunnelData == NULL);
  611. FTunnelLocalPortNumber = FSessionData->TunnelLocalPortNumber;
  612. if (FTunnelLocalPortNumber == 0)
  613. {
  614. TGuard Guard(&FSection);
  615. FTunnelLocalPortNumber = Configuration->TunnelLocalPortNumberLow;
  616. // override strange bug in STL
  617. #pragma warn -8092
  618. while ((FTunnelLocalPorts.find(FTunnelLocalPortNumber) != FTunnelLocalPorts.end()) ||
  619. !IsListenerFree(FTunnelLocalPortNumber))
  620. #pragma warn .8092
  621. {
  622. FTunnelLocalPortNumber++;
  623. if (FTunnelLocalPortNumber > Configuration->TunnelLocalPortNumberHigh)
  624. {
  625. FTunnelLocalPortNumber = 0;
  626. FatalError(NULL, FMTLOAD(TUNNEL_NO_FREE_PORT,
  627. (Configuration->TunnelLocalPortNumberLow, Configuration->TunnelLocalPortNumberHigh)));
  628. }
  629. }
  630. FTunnelLocalPorts.insert(FTunnelLocalPortNumber);
  631. LogEvent(FORMAT("Autoselected tunnel local port number %d", (FTunnelLocalPortNumber)));
  632. }
  633. try
  634. {
  635. FTunnelData = new TSessionData("");
  636. FTunnelData->Assign(StoredSessions->DefaultSettings);
  637. FTunnelData->Name = FMTLOAD(TUNNEL_SESSION_NAME, (FSessionData->SessionName));
  638. FTunnelData->Tunnel = false;
  639. FTunnelData->HostName = FSessionData->TunnelHostName;
  640. FTunnelData->PortNumber = FSessionData->TunnelPortNumber;
  641. FTunnelData->UserName = FSessionData->TunnelUserName;
  642. FTunnelData->Password = FSessionData->TunnelPassword;
  643. FTunnelData->PublicKeyFile = FSessionData->TunnelPublicKeyFile;
  644. FTunnelData->TunnelPortFwd = FORMAT("L%d\t%s:%d",
  645. (FTunnelLocalPortNumber, FSessionData->HostName, FSessionData->PortNumber));
  646. FTunnelData->ProxyMethod = FSessionData->ProxyMethod;
  647. FTunnelData->ProxyHost = FSessionData->ProxyHost;
  648. FTunnelData->ProxyPort = FSessionData->ProxyPort;
  649. FTunnelData->ProxyUsername = FSessionData->ProxyUsername;
  650. FTunnelData->ProxyPassword = FSessionData->ProxyPassword;
  651. FTunnelData->ProxyTelnetCommand = FSessionData->ProxyTelnetCommand;
  652. FTunnelData->ProxyDNS = FSessionData->ProxyDNS;
  653. FTunnelData->ProxyLocalhost = FSessionData->ProxyLocalhost;
  654. FTunnelLog = new TSessionLog(this, FTunnelData, Configuration);
  655. FTunnelLog->Parent = FLog;
  656. FTunnelLog->Name = "Tunnel";
  657. FTunnelUI = new TTunnelUI(this);
  658. FTunnel = new TSecureShell(FTunnelUI, FTunnelData, FTunnelLog, Configuration);
  659. FTunnel->Open();
  660. FTunnelThread = new TTunnelThread(FTunnel);
  661. }
  662. catch(...)
  663. {
  664. CloseTunnel();
  665. throw;
  666. }
  667. }
  668. //---------------------------------------------------------------------------
  669. void __fastcall TTerminal::CloseTunnel()
  670. {
  671. SAFE_DESTROY_EX(TTunnelThread, FTunnelThread);
  672. FTunnelError = FTunnel->LastTunnelError;
  673. SAFE_DESTROY_EX(TSecureShell, FTunnel);
  674. SAFE_DESTROY_EX(TTunnelUI, FTunnelUI);
  675. SAFE_DESTROY_EX(TSessionLog, FTunnelLog);
  676. SAFE_DESTROY(FTunnelData);
  677. TGuard Guard(&FSection);
  678. FTunnelLocalPorts.erase(FTunnelLocalPortNumber);
  679. FTunnelLocalPortNumber = 0;
  680. }
  681. //---------------------------------------------------------------------------
  682. void __fastcall TTerminal::Closed()
  683. {
  684. if (FTunnel != NULL)
  685. {
  686. CloseTunnel();
  687. }
  688. if (OnClose)
  689. {
  690. OnClose(this);
  691. }
  692. FStatus = ssClosed;
  693. }
  694. //---------------------------------------------------------------------------
  695. void __fastcall TTerminal::Reopen(int Params)
  696. {
  697. assert(FExceptionOnFail == 0);
  698. TFSProtocol OrigFSProtocol = SessionData->FSProtocol;
  699. AnsiString PrevRemoteDirectory = SessionData->RemoteDirectory;
  700. bool PrevReadCurrentDirectoryPending = FReadCurrentDirectoryPending;
  701. bool PrevReadDirectoryPending = FReadDirectoryPending;
  702. int PrevInTransaction = FInTransaction;
  703. bool PrevAutoReadDirectory = FAutoReadDirectory;
  704. try
  705. {
  706. FReadCurrentDirectoryPending = false;
  707. FReadDirectoryPending = false;
  708. FInTransaction = 0;
  709. // typically, we avoid reading directory, when there is operation ongoing,
  710. // for file list which may reference files from current directory
  711. if (FLAGSET(Params, ropNoReadDirectory))
  712. {
  713. AutoReadDirectory = false;
  714. }
  715. SessionData->RemoteDirectory = CurrentDirectory;
  716. if (SessionData->FSProtocol == fsSFTP)
  717. {
  718. SessionData->FSProtocol = (FFSProtocol == cfsSCP ? fsSCPonly : fsSFTPonly);
  719. }
  720. if (Active)
  721. {
  722. Close();
  723. }
  724. Open();
  725. }
  726. __finally
  727. {
  728. SessionData->RemoteDirectory = PrevRemoteDirectory;
  729. SessionData->FSProtocol = OrigFSProtocol;
  730. FAutoReadDirectory = PrevAutoReadDirectory;
  731. FReadCurrentDirectoryPending = PrevReadCurrentDirectoryPending;
  732. FReadDirectoryPending = PrevReadDirectoryPending;
  733. FInTransaction = PrevInTransaction;
  734. }
  735. }
  736. //---------------------------------------------------------------------------
  737. bool __fastcall TTerminal::PromptUser(TSessionData * Data, AnsiString Prompt,
  738. TPromptKind Kind, AnsiString & Response)
  739. {
  740. // If PromptUser is overriden in descendant class, the overriden version
  741. // is not called when accessed via TSessionIU interface.
  742. // So this is workaround.
  743. return DoPromptUser(Data, Prompt, Kind, Response);
  744. }
  745. //---------------------------------------------------------------------------
  746. bool __fastcall TTerminal::DoPromptUser(TSessionData * /*Data*/, AnsiString Prompt,
  747. TPromptKind Kind, AnsiString & Response)
  748. {
  749. bool Result = false;
  750. if (OnPromptUser != NULL)
  751. {
  752. OnPromptUser(this, Prompt, Kind, Response, Result, NULL);
  753. }
  754. if ((Configuration->RememberPassword) &&
  755. ((Kind == pkPassword) || (Kind == pkPassphrase) || (Kind == pkServerPrompt)))
  756. {
  757. FPassword = EncryptPassword(Response, SessionData->SessionName);
  758. }
  759. return Result;
  760. }
  761. //---------------------------------------------------------------------------
  762. int __fastcall TTerminal::QueryUser(const AnsiString Query,
  763. TStrings * MoreMessages, int Answers, const TQueryParams * Params,
  764. TQueryType QueryType)
  765. {
  766. LogEvent(FORMAT("Asking user:\n%s (%s)", (Query, (MoreMessages ? MoreMessages->CommaText : AnsiString() ))));
  767. int Answer = AbortAnswer(Answers);
  768. if (FOnQueryUser)
  769. {
  770. FOnQueryUser(this, Query, MoreMessages, Answers, Params, Answer, QueryType, NULL);
  771. }
  772. return Answer;
  773. }
  774. //---------------------------------------------------------------------------
  775. int __fastcall TTerminal::QueryUserException(const AnsiString Query,
  776. Exception * E, int Answers, const TQueryParams * Params,
  777. TQueryType QueryType)
  778. {
  779. int Result;
  780. TStrings * MoreMessages = new TStringList();
  781. try
  782. {
  783. if (!E->Message.IsEmpty() && !Query.IsEmpty())
  784. {
  785. MoreMessages->Add(E->Message);
  786. }
  787. ExtException * EE = dynamic_cast<ExtException*>(E);
  788. if ((EE != NULL) && (EE->MoreMessages != NULL))
  789. {
  790. MoreMessages->AddStrings(EE->MoreMessages);
  791. }
  792. Result = QueryUser(!Query.IsEmpty() ? Query : E->Message,
  793. MoreMessages->Count ? MoreMessages : NULL,
  794. Answers, Params, QueryType);
  795. }
  796. __finally
  797. {
  798. delete MoreMessages;
  799. }
  800. return Result;
  801. }
  802. //---------------------------------------------------------------------------
  803. void __fastcall TTerminal::DisplayBanner(const AnsiString & Banner)
  804. {
  805. if (OnDisplayBanner != NULL)
  806. {
  807. if (Configuration->ForceBanners ||
  808. Configuration->ShowBanner(SessionData->SessionKey, Banner))
  809. {
  810. bool NeverShowAgain = false;
  811. int Options =
  812. FLAGMASK(Configuration->ForceBanners, boDisableNeverShowAgain);
  813. OnDisplayBanner(this, SessionData->SessionName, Banner,
  814. NeverShowAgain, Options);
  815. if (!Configuration->ForceBanners && NeverShowAgain)
  816. {
  817. Configuration->NeverShowBanner(SessionData->SessionKey, Banner);
  818. }
  819. }
  820. }
  821. }
  822. //---------------------------------------------------------------------------
  823. void __fastcall TTerminal::ShowExtendedException(Exception * E)
  824. {
  825. Log->AddException(E);
  826. if (OnShowExtendedException != NULL)
  827. {
  828. OnShowExtendedException(this, E, NULL);
  829. }
  830. }
  831. //---------------------------------------------------------------------------
  832. void __fastcall TTerminal::DoInformation(const AnsiString & Str, bool Status,
  833. bool Active)
  834. {
  835. if (Active)
  836. {
  837. FAnyInformation = true;
  838. }
  839. if (OnInformation)
  840. {
  841. OnInformation(this, Str, Status, Active);
  842. }
  843. }
  844. //---------------------------------------------------------------------------
  845. void __fastcall TTerminal::Information(const AnsiString & Str, bool Status)
  846. {
  847. DoInformation(Str, Status);
  848. }
  849. //---------------------------------------------------------------------------
  850. bool __fastcall TTerminal::GetIsCapable(TFSCapability Capability) const
  851. {
  852. assert(FFileSystem);
  853. return FFileSystem->IsCapable(Capability);
  854. }
  855. //---------------------------------------------------------------------------
  856. AnsiString __fastcall TTerminal::AbsolutePath(AnsiString Path)
  857. {
  858. return FFileSystem->AbsolutePath(Path);
  859. }
  860. //---------------------------------------------------------------------------
  861. void __fastcall TTerminal::ReactOnCommand(int /*TFSCommand*/ Cmd)
  862. {
  863. bool ChangesDirectory = false;
  864. bool ModifiesFiles = false;
  865. switch ((TFSCommand)Cmd) {
  866. case fsChangeDirectory:
  867. case fsHomeDirectory:
  868. ChangesDirectory = true;
  869. break;
  870. case fsCopyToRemote:
  871. case fsDeleteFile:
  872. case fsRenameFile:
  873. case fsMoveFile:
  874. case fsCopyFile:
  875. case fsCreateDirectory:
  876. case fsChangeMode:
  877. case fsChangeGroup:
  878. case fsChangeOwner:
  879. case fsChangeProperties:
  880. ModifiesFiles = true;
  881. break;
  882. case fsAnyCommand:
  883. ChangesDirectory = true;
  884. ModifiesFiles = true;
  885. break;
  886. }
  887. if (ChangesDirectory)
  888. {
  889. if (!FInTransaction)
  890. {
  891. ReadCurrentDirectory();
  892. if (AutoReadDirectory)
  893. {
  894. ReadDirectory(false);
  895. }
  896. }
  897. else
  898. {
  899. FReadCurrentDirectoryPending = true;
  900. if (AutoReadDirectory)
  901. {
  902. FReadDirectoryPending = true;
  903. }
  904. }
  905. }
  906. else
  907. if (ModifiesFiles && AutoReadDirectory && Configuration->AutoReadDirectoryAfterOp)
  908. {
  909. if (!FInTransaction) ReadDirectory(true);
  910. else FReadDirectoryPending = true;
  911. }
  912. }
  913. //---------------------------------------------------------------------------
  914. void __fastcall TTerminal::TerminalError(AnsiString Msg)
  915. {
  916. TerminalError(NULL, Msg);
  917. }
  918. //---------------------------------------------------------------------------
  919. void __fastcall TTerminal::TerminalError(Exception * E, AnsiString Msg)
  920. {
  921. throw ETerminal(E, Msg);
  922. }
  923. //---------------------------------------------------------------------------
  924. bool __fastcall TTerminal::DoQueryReopen(Exception * E)
  925. {
  926. LogEvent("Connection was lost, asking what to do.");
  927. TQueryParams Params(qpAllowContinueOnError);
  928. Params.Timeout = Configuration->SessionReopenAuto;
  929. Params.TimeoutAnswer = qaRetry;
  930. TQueryButtonAlias Aliases[1];
  931. Aliases[0].Button = qaRetry;
  932. Aliases[0].Alias = LoadStr(RECONNECT_BUTTON);
  933. Params.Aliases = Aliases;
  934. Params.AliasesCount = LENOF(Aliases);
  935. return (QueryUserException("", E, qaRetry | qaAbort, &Params, qtError) == qaRetry);
  936. }
  937. //---------------------------------------------------------------------------
  938. bool __fastcall TTerminal::QueryReopen(Exception * E, int Params,
  939. TFileOperationProgressType * OperationProgress)
  940. {
  941. TSuspendFileOperationProgress Suspend(OperationProgress);
  942. bool Result = DoQueryReopen(E);
  943. if (Result)
  944. {
  945. do
  946. {
  947. try
  948. {
  949. Reopen(Params);
  950. }
  951. catch(Exception & E)
  952. {
  953. if (!Active)
  954. {
  955. Result = DoQueryReopen(&E);
  956. }
  957. else
  958. {
  959. throw;
  960. }
  961. }
  962. }
  963. while (!Active && Result);
  964. }
  965. return Result;
  966. }
  967. //---------------------------------------------------------------------------
  968. bool __fastcall TTerminal::FileOperationLoopQuery(Exception & E,
  969. TFileOperationProgressType * OperationProgress, const AnsiString Message,
  970. bool AllowSkip, AnsiString SpecialRetry)
  971. {
  972. bool Result = false;
  973. Log->AddException(&E);
  974. int Answer;
  975. if (AllowSkip && OperationProgress->SkipToAll)
  976. {
  977. Answer = qaSkip;
  978. }
  979. else
  980. {
  981. int Answers = qaRetry | qaAbort |
  982. FLAGMASK(AllowSkip, (qaSkip | qaAll)) |
  983. FLAGMASK(!SpecialRetry.IsEmpty(), qaYes);
  984. TQueryParams Params(qpAllowContinueOnError | FLAGMASK(!AllowSkip, qpFatalAbort));
  985. TQueryButtonAlias Aliases[2];
  986. int AliasCount = 0;
  987. if (FLAGSET(Answers, qaAll))
  988. {
  989. Aliases[AliasCount].Button = qaAll;
  990. Aliases[AliasCount].Alias = LoadStr(SKIP_ALL_BUTTON);
  991. AliasCount++;
  992. }
  993. if (FLAGSET(Answers, qaYes))
  994. {
  995. Aliases[AliasCount].Button = qaYes;
  996. Aliases[AliasCount].Alias = SpecialRetry;
  997. AliasCount++;
  998. }
  999. if (AliasCount > 0)
  1000. {
  1001. Params.Aliases = Aliases;
  1002. Params.AliasesCount = AliasCount;
  1003. }
  1004. SUSPEND_OPERATION (
  1005. Answer = QueryUserException(Message, &E, Answers, &Params, qtError);
  1006. );
  1007. if (Answer == qaAll)
  1008. {
  1009. OperationProgress->SkipToAll = true;
  1010. Answer = qaSkip;
  1011. }
  1012. if (Answer == qaYes)
  1013. {
  1014. Result = true;
  1015. Answer = qaRetry;
  1016. }
  1017. }
  1018. if (Answer != qaRetry)
  1019. {
  1020. if (Answer == qaAbort)
  1021. {
  1022. OperationProgress->Cancel = csCancel;
  1023. }
  1024. if (AllowSkip)
  1025. {
  1026. THROW_SKIP_FILE(&E, Message);
  1027. }
  1028. else
  1029. {
  1030. // this can happen only during file transfer with SCP
  1031. throw ExtException(&E, Message);
  1032. }
  1033. }
  1034. return Result;
  1035. }
  1036. //---------------------------------------------------------------------------
  1037. int __fastcall TTerminal::FileOperationLoop(TFileOperationEvent CallBackFunc,
  1038. TFileOperationProgressType * OperationProgress, bool AllowSkip,
  1039. const AnsiString Message, void * Param1, void * Param2)
  1040. {
  1041. assert(CallBackFunc);
  1042. int Result;
  1043. FILE_OPERATION_LOOP_EX
  1044. (
  1045. AllowSkip, Message,
  1046. Result = CallBackFunc(Param1, Param2);
  1047. );
  1048. return Result;
  1049. }
  1050. //---------------------------------------------------------------------------
  1051. AnsiString __fastcall TTerminal::TranslateLockedPath(AnsiString Path, bool Lock)
  1052. {
  1053. if (!SessionData->LockInHome || Path.IsEmpty() || (Path[1] != '/'))
  1054. return Path;
  1055. if (Lock)
  1056. {
  1057. if (Path.SubString(1, FLockDirectory.Length()) == FLockDirectory)
  1058. {
  1059. Path.Delete(1, FLockDirectory.Length());
  1060. if (Path.IsEmpty()) Path = "/";
  1061. }
  1062. }
  1063. else
  1064. {
  1065. Path = UnixExcludeTrailingBackslash(FLockDirectory + Path);
  1066. }
  1067. return Path;
  1068. }
  1069. //---------------------------------------------------------------------------
  1070. void __fastcall TTerminal::ClearCaches()
  1071. {
  1072. FDirectoryCache->Clear();
  1073. if (FDirectoryChangesCache != NULL)
  1074. {
  1075. FDirectoryChangesCache->Clear();
  1076. }
  1077. }
  1078. //---------------------------------------------------------------------------
  1079. void __fastcall TTerminal::ClearCachedFileList(const AnsiString Path,
  1080. bool SubDirs)
  1081. {
  1082. FDirectoryCache->ClearFileList(Path, SubDirs);
  1083. }
  1084. //---------------------------------------------------------------------------
  1085. void __fastcall TTerminal::AddCachedFileList(TRemoteFileList * FileList)
  1086. {
  1087. FDirectoryCache->AddFileList(FileList);
  1088. }
  1089. //---------------------------------------------------------------------------
  1090. bool __fastcall TTerminal::DirectoryFileList(const AnsiString Path,
  1091. TRemoteFileList *& FileList, bool CanLoad)
  1092. {
  1093. bool Result = false;
  1094. if (UnixComparePaths(FFiles->Directory, Path))
  1095. {
  1096. Result = (FileList == NULL) || (FileList->Timestamp < FFiles->Timestamp);
  1097. if (Result)
  1098. {
  1099. if (FileList == NULL)
  1100. {
  1101. FileList = new TRemoteFileList();
  1102. }
  1103. FFiles->DuplicateTo(FileList);
  1104. }
  1105. }
  1106. else
  1107. {
  1108. if (((FileList == NULL) && FDirectoryCache->HasFileList(Path)) ||
  1109. ((FileList != NULL) && FDirectoryCache->HasNewerFileList(Path, FileList->Timestamp)))
  1110. {
  1111. bool Created = (FileList == NULL);
  1112. if (Created)
  1113. {
  1114. FileList = new TRemoteFileList();
  1115. }
  1116. Result = FDirectoryCache->GetFileList(Path, FileList);
  1117. if (!Result && Created)
  1118. {
  1119. SAFE_DESTROY(FileList);
  1120. }
  1121. }
  1122. // do not attempt to load file list if there is cached version,
  1123. // only absence of cached version indicates that we consider
  1124. // the directory content obsolete
  1125. else if (CanLoad && !FDirectoryCache->HasFileList(Path))
  1126. {
  1127. bool Created = (FileList == NULL);
  1128. if (Created)
  1129. {
  1130. FileList = new TRemoteFileList();
  1131. }
  1132. FileList->Directory = Path;
  1133. try
  1134. {
  1135. ReadDirectory(FileList);
  1136. Result = true;
  1137. }
  1138. catch(...)
  1139. {
  1140. if (Created)
  1141. {
  1142. SAFE_DESTROY(FileList);
  1143. }
  1144. throw;
  1145. }
  1146. }
  1147. }
  1148. return Result;
  1149. }
  1150. //---------------------------------------------------------------------------
  1151. void __fastcall TTerminal::SetCurrentDirectory(AnsiString value)
  1152. {
  1153. assert(FFileSystem);
  1154. value = TranslateLockedPath(value, false);
  1155. if (value != FFileSystem->CurrentDirectory)
  1156. {
  1157. ChangeDirectory(value);
  1158. }
  1159. }
  1160. //---------------------------------------------------------------------------
  1161. AnsiString __fastcall TTerminal::GetCurrentDirectory()
  1162. {
  1163. if (FFileSystem)
  1164. {
  1165. FCurrentDirectory = FFileSystem->CurrentDirectory;
  1166. if (FCurrentDirectory.IsEmpty())
  1167. {
  1168. ReadCurrentDirectory();
  1169. }
  1170. }
  1171. return TranslateLockedPath(FCurrentDirectory, true);
  1172. }
  1173. //---------------------------------------------------------------------------
  1174. AnsiString __fastcall TTerminal::PeekCurrentDirectory()
  1175. {
  1176. if (FFileSystem)
  1177. {
  1178. FCurrentDirectory = FFileSystem->CurrentDirectory;
  1179. }
  1180. return TranslateLockedPath(FCurrentDirectory, true);
  1181. }
  1182. //---------------------------------------------------------------------------
  1183. TUsersGroupsList * __fastcall TTerminal::GetGroups()
  1184. {
  1185. assert(FFileSystem);
  1186. if (!FUsersGroupsLookedup && SessionData->LookupUserGroups &&
  1187. IsCapable[fcUserGroupListing])
  1188. {
  1189. LookupUsersGroups();
  1190. }
  1191. return FGroups;
  1192. }
  1193. //---------------------------------------------------------------------------
  1194. TUsersGroupsList * __fastcall TTerminal::GetUsers()
  1195. {
  1196. assert(FFileSystem);
  1197. if (!FUsersGroupsLookedup && SessionData->LookupUserGroups &&
  1198. IsCapable[fcUserGroupListing])
  1199. {
  1200. LookupUsersGroups();
  1201. }
  1202. return FUsers;
  1203. }
  1204. //---------------------------------------------------------------------------
  1205. AnsiString __fastcall TTerminal::GetUserName() const
  1206. {
  1207. // in future might also be implemented to detect username similar to GetUserGroups
  1208. assert(FFileSystem != NULL);
  1209. AnsiString Result = FFileSystem->GetUserName();
  1210. // Is empty also when stored password was used
  1211. if (Result.IsEmpty())
  1212. {
  1213. Result = SessionData->UserName;
  1214. }
  1215. return Result;
  1216. }
  1217. //---------------------------------------------------------------------------
  1218. bool __fastcall TTerminal::GetAreCachesEmpty() const
  1219. {
  1220. return FDirectoryCache->IsEmpty &&
  1221. ((FDirectoryChangesCache == NULL) || FDirectoryChangesCache->IsEmpty);
  1222. }
  1223. //---------------------------------------------------------------------------
  1224. void __fastcall TTerminal::DoChangeDirectory()
  1225. {
  1226. if (FOnChangeDirectory)
  1227. {
  1228. FOnChangeDirectory(this);
  1229. }
  1230. }
  1231. //---------------------------------------------------------------------------
  1232. void __fastcall TTerminal::DoReadDirectory(bool ReloadOnly)
  1233. {
  1234. if (FOnReadDirectory)
  1235. {
  1236. FOnReadDirectory(this, ReloadOnly);
  1237. }
  1238. }
  1239. //---------------------------------------------------------------------------
  1240. void __fastcall TTerminal::DoStartReadDirectory()
  1241. {
  1242. if (FOnStartReadDirectory)
  1243. {
  1244. FOnStartReadDirectory(this);
  1245. }
  1246. }
  1247. //---------------------------------------------------------------------------
  1248. void __fastcall TTerminal::DoReadDirectoryProgress(int Progress, bool & Cancel)
  1249. {
  1250. if (FReadingCurrentDirectory && (FOnReadDirectoryProgress != NULL))
  1251. {
  1252. FOnReadDirectoryProgress(this, Progress, Cancel);
  1253. }
  1254. }
  1255. //---------------------------------------------------------------------------
  1256. void __fastcall TTerminal::BeginTransaction()
  1257. {
  1258. if (!FInTransaction)
  1259. {
  1260. FReadCurrentDirectoryPending = false;
  1261. FReadDirectoryPending = false;
  1262. }
  1263. FInTransaction++;
  1264. if (FCommandSession != NULL)
  1265. {
  1266. FCommandSession->BeginTransaction();
  1267. }
  1268. }
  1269. //---------------------------------------------------------------------------
  1270. void __fastcall TTerminal::EndTransaction()
  1271. {
  1272. if (!FInTransaction)
  1273. TerminalError("Can't end transaction, not in transaction");
  1274. assert(FInTransaction > 0);
  1275. FInTransaction--;
  1276. // it connection was closed due to fatal error during transaction, do nothing
  1277. if (Active)
  1278. {
  1279. if (FInTransaction == 0)
  1280. {
  1281. try
  1282. {
  1283. if (FReadCurrentDirectoryPending) ReadCurrentDirectory();
  1284. if (FReadDirectoryPending) ReadDirectory(!FReadCurrentDirectoryPending);
  1285. }
  1286. __finally
  1287. {
  1288. FReadCurrentDirectoryPending = false;
  1289. FReadDirectoryPending = false;
  1290. }
  1291. }
  1292. }
  1293. if (FCommandSession != NULL)
  1294. {
  1295. FCommandSession->EndTransaction();
  1296. }
  1297. }
  1298. //---------------------------------------------------------------------------
  1299. void __fastcall TTerminal::SetExceptionOnFail(bool value)
  1300. {
  1301. if (value) FExceptionOnFail++;
  1302. else
  1303. {
  1304. if (FExceptionOnFail == 0)
  1305. throw Exception("ExceptionOnFail is already zero.");
  1306. FExceptionOnFail--;
  1307. }
  1308. if (FCommandSession != NULL)
  1309. {
  1310. FCommandSession->FExceptionOnFail = FExceptionOnFail;
  1311. }
  1312. }
  1313. //---------------------------------------------------------------------------
  1314. bool __fastcall TTerminal::GetExceptionOnFail() const
  1315. {
  1316. return (bool)(FExceptionOnFail > 0);
  1317. }
  1318. //---------------------------------------------------------------------------
  1319. void __fastcall TTerminal::FatalError(Exception * E, AnsiString Msg)
  1320. {
  1321. // the same code is in TSecureShell
  1322. if (Active)
  1323. {
  1324. // We log this instead of exception handler, because Close() would
  1325. // probably cause exception handler to loose pointer to TShellLog()
  1326. LogEvent("Attempt to close connection due to fatal exception:");
  1327. Log->Add(llException, Msg);
  1328. Log->AddException(E);
  1329. Close();
  1330. }
  1331. SSH_FATAL_ERROR_EXT(E, Msg);
  1332. }
  1333. //---------------------------------------------------------------------------
  1334. void __fastcall TTerminal::CommandError(Exception * E, const AnsiString Msg)
  1335. {
  1336. CommandError(E, Msg, 0);
  1337. }
  1338. //---------------------------------------------------------------------------
  1339. int __fastcall TTerminal::CommandError(Exception * E, const AnsiString Msg,
  1340. int Answers)
  1341. {
  1342. int Result = 0;
  1343. if (E && E->InheritsFrom(__classid(EFatal)))
  1344. {
  1345. FatalError(E, Msg);
  1346. }
  1347. else if (E && E->InheritsFrom(__classid(EAbort)))
  1348. {
  1349. // resent EAbort exception
  1350. Abort();
  1351. }
  1352. else if (ExceptionOnFail)
  1353. {
  1354. throw ECommand(E, Msg);
  1355. }
  1356. else if (!Answers)
  1357. {
  1358. ECommand * ECmd = new ECommand(E, Msg);
  1359. try
  1360. {
  1361. ShowExtendedException(ECmd);
  1362. }
  1363. __finally
  1364. {
  1365. delete ECmd;
  1366. }
  1367. }
  1368. else
  1369. {
  1370. // small hack to anable "skip to all" for COMMAND_ERROR_ARI
  1371. bool CanSkip = FLAGSET(Answers, qaSkip) && (OperationProgress != NULL);
  1372. if (CanSkip && OperationProgress->SkipToAll)
  1373. {
  1374. Result = qaSkip;
  1375. }
  1376. else
  1377. {
  1378. TQueryParams Params(qpAllowContinueOnError);
  1379. TQueryButtonAlias Aliases[1];
  1380. if (CanSkip)
  1381. {
  1382. Aliases[0].Button = qaAll;
  1383. Aliases[0].Alias = LoadStr(SKIP_ALL_BUTTON);
  1384. Params.Aliases = Aliases;
  1385. Params.AliasesCount = LENOF(Aliases);
  1386. Answers |= qaAll;
  1387. }
  1388. Result = QueryUserException(Msg, E, Answers, &Params, qtError);
  1389. if (Result == qaAll)
  1390. {
  1391. assert(OperationProgress != NULL);
  1392. OperationProgress->SkipToAll = true;
  1393. Result = qaSkip;
  1394. }
  1395. }
  1396. }
  1397. return Result;
  1398. }
  1399. //---------------------------------------------------------------------------
  1400. bool __fastcall TTerminal::HandleException(Exception * E)
  1401. {
  1402. if (ExceptionOnFail)
  1403. {
  1404. return false;
  1405. }
  1406. else
  1407. {
  1408. Log->AddException(E);
  1409. return true;
  1410. }
  1411. }
  1412. //---------------------------------------------------------------------------
  1413. void __fastcall TTerminal::CloseOnCompletion(const AnsiString Message)
  1414. {
  1415. LogEvent("Closing session after completed operation (as requested by user)");
  1416. Close();
  1417. throw ESshTerminate(NULL,
  1418. Message.IsEmpty() ? LoadStr(CLOSED_ON_COMPLETION) : Message);
  1419. }
  1420. //---------------------------------------------------------------------------
  1421. int __fastcall TTerminal::ConfirmFileOverwrite(const AnsiString FileName,
  1422. const TOverwriteFileParams * FileParams, int Answers, const TQueryParams * Params,
  1423. TOperationSide Side, TFileOperationProgressType * OperationProgress)
  1424. {
  1425. int Answer;
  1426. int AnswerForNewer =
  1427. (CompareFileTime(FileParams->SourceTimestamp, FileParams->DestTimestamp) > 0) ?
  1428. qaYes : qaNo;
  1429. if (OperationProgress->YesToNewer)
  1430. {
  1431. Answer = AnswerForNewer;
  1432. }
  1433. else
  1434. {
  1435. AnsiString Message = FMTLOAD((Side == osLocal ? LOCAL_FILE_OVERWRITE :
  1436. REMOTE_FILE_OVERWRITE), (FileName));
  1437. if (FileParams)
  1438. {
  1439. Message = FMTLOAD(FILE_OVERWRITE_DETAILS, (Message,
  1440. IntToStr(FileParams->SourceSize),
  1441. UserModificationStr(FileParams->SourceTimestamp, FileParams->SourcePrecision),
  1442. IntToStr(FileParams->DestSize),
  1443. UserModificationStr(FileParams->DestTimestamp, FileParams->DestPrecision)));
  1444. }
  1445. Answer = QueryUser(Message, NULL, Answers, Params);
  1446. switch (Answer)
  1447. {
  1448. case qaNeverAskAgain:
  1449. Configuration->ConfirmOverwriting = false;
  1450. Answer = qaYes;
  1451. break;
  1452. case qaYesToAll:
  1453. OperationProgress->YesToAll = true;
  1454. Answer = qaYes;
  1455. break;
  1456. case qaAll:
  1457. OperationProgress->YesToNewer = true;
  1458. Answer = AnswerForNewer;
  1459. break;
  1460. case qaNoToAll:
  1461. OperationProgress->NoToAll = true;
  1462. Answer = qaNo;
  1463. }
  1464. }
  1465. return Answer;
  1466. }
  1467. //---------------------------------------------------------------------------
  1468. void __fastcall TTerminal::FileModified(const TRemoteFile * File,
  1469. const AnsiString FileName, bool ClearDirectoryChange)
  1470. {
  1471. AnsiString ParentDirectory;
  1472. AnsiString Directory;
  1473. if (SessionData->CacheDirectories || SessionData->CacheDirectoryChanges)
  1474. {
  1475. if ((File != NULL) && (File->Directory != NULL))
  1476. {
  1477. if (File->IsDirectory)
  1478. {
  1479. Directory = File->Directory->FullDirectory + File->FileName;
  1480. }
  1481. ParentDirectory = File->Directory->Directory;
  1482. }
  1483. else if (!FileName.IsEmpty())
  1484. {
  1485. ParentDirectory = UnixExtractFilePath(FileName);
  1486. if (ParentDirectory.IsEmpty())
  1487. {
  1488. ParentDirectory = CurrentDirectory;
  1489. }
  1490. // this case for scripting
  1491. if ((File != NULL) && File->IsDirectory)
  1492. {
  1493. Directory = UnixIncludeTrailingBackslash(ParentDirectory) +
  1494. UnixExtractFileName(File->FileName);
  1495. }
  1496. }
  1497. }
  1498. if (SessionData->CacheDirectories)
  1499. {
  1500. if (!Directory.IsEmpty())
  1501. {
  1502. DirectoryModified(Directory, true);
  1503. }
  1504. if (!ParentDirectory.IsEmpty())
  1505. {
  1506. DirectoryModified(ParentDirectory, false);
  1507. }
  1508. }
  1509. if (SessionData->CacheDirectoryChanges && ClearDirectoryChange)
  1510. {
  1511. if (!Directory.IsEmpty())
  1512. {
  1513. FDirectoryChangesCache->ClearDirectoryChange(Directory);
  1514. FDirectoryChangesCache->ClearDirectoryChangeTarget(Directory);
  1515. }
  1516. }
  1517. }
  1518. //---------------------------------------------------------------------------
  1519. void __fastcall TTerminal::DoDirectoryModified(const AnsiString Path, bool SubDirs)
  1520. {
  1521. if (OnDirectoryModified != NULL)
  1522. {
  1523. OnDirectoryModified(this, Path, SubDirs);
  1524. }
  1525. }
  1526. //---------------------------------------------------------------------------
  1527. void __fastcall TTerminal::DirectoryModified(const AnsiString Path, bool SubDirs)
  1528. {
  1529. if (Path.IsEmpty())
  1530. {
  1531. ClearCachedFileList(CurrentDirectory, SubDirs);
  1532. }
  1533. else
  1534. {
  1535. ClearCachedFileList(Path, SubDirs);
  1536. }
  1537. DoDirectoryModified(Path, SubDirs);
  1538. }
  1539. //---------------------------------------------------------------------------
  1540. void __fastcall TTerminal::DirectoryLoaded(TRemoteFileList * FileList)
  1541. {
  1542. AddCachedFileList(FileList);
  1543. }
  1544. //---------------------------------------------------------------------------
  1545. void __fastcall TTerminal::ReloadDirectory()
  1546. {
  1547. if (SessionData->CacheDirectories)
  1548. {
  1549. DirectoryModified(CurrentDirectory, false);
  1550. }
  1551. if (SessionData->CacheDirectoryChanges)
  1552. {
  1553. assert(FDirectoryChangesCache != NULL);
  1554. FDirectoryChangesCache->ClearDirectoryChange(CurrentDirectory);
  1555. }
  1556. ReadCurrentDirectory();
  1557. FReadCurrentDirectoryPending = false;
  1558. ReadDirectory(true);
  1559. FReadDirectoryPending = false;
  1560. }
  1561. //---------------------------------------------------------------------------
  1562. void __fastcall TTerminal::RefreshDirectory()
  1563. {
  1564. if (SessionData->CacheDirectories &&
  1565. FDirectoryCache->HasNewerFileList(CurrentDirectory, FFiles->Timestamp))
  1566. {
  1567. // Second parameter was added to allow (rather force) using the cache.
  1568. // Before, the directory was reloaded always, it seems useless,
  1569. // has it any reason?
  1570. ReadDirectory(true, true);
  1571. FReadDirectoryPending = false;
  1572. }
  1573. }
  1574. //---------------------------------------------------------------------------
  1575. void __fastcall TTerminal::EnsureNonExistence(const AnsiString FileName)
  1576. {
  1577. // if filename doesn't contain path, we check for existence of file
  1578. if ((UnixExtractFileDir(FileName).IsEmpty()) &&
  1579. UnixComparePaths(CurrentDirectory, FFiles->Directory))
  1580. {
  1581. TRemoteFile *File = FFiles->FindFile(FileName);
  1582. if (File)
  1583. {
  1584. if (File->IsDirectory) throw ECommand(NULL, FMTLOAD(RENAME_CREATE_DIR_EXISTS, (FileName)));
  1585. else throw ECommand(NULL, FMTLOAD(RENAME_CREATE_FILE_EXISTS, (FileName)));
  1586. }
  1587. }
  1588. }
  1589. //---------------------------------------------------------------------------
  1590. void __fastcall inline TTerminal::LogEvent(const AnsiString & Str)
  1591. {
  1592. if (Log->Logging)
  1593. {
  1594. Log->Add(llMessage, Str);
  1595. }
  1596. }
  1597. //---------------------------------------------------------------------------
  1598. void __fastcall TTerminal::DoStartup()
  1599. {
  1600. LogEvent("Doing startup conversation with host.");
  1601. BeginTransaction();
  1602. try
  1603. {
  1604. DoInformation(LoadStr(STATUS_STARTUP), true);
  1605. // Make sure that directory would be loaded at last
  1606. FReadCurrentDirectoryPending = true;
  1607. FReadDirectoryPending = AutoReadDirectory;
  1608. FFileSystem->DoStartup();
  1609. if (SessionData->LookupUserGroups && IsCapable[fcUserGroupListing])
  1610. {
  1611. LookupUsersGroups();
  1612. }
  1613. DoInformation(LoadStr(STATUS_OPEN_DIRECTORY), true);
  1614. if (!SessionData->RemoteDirectory.IsEmpty())
  1615. {
  1616. ChangeDirectory(SessionData->RemoteDirectory);
  1617. }
  1618. }
  1619. __finally
  1620. {
  1621. EndTransaction();
  1622. }
  1623. LogEvent("Startup conversation with host finished.");
  1624. }
  1625. //---------------------------------------------------------------------------
  1626. void __fastcall TTerminal::ReadCurrentDirectory()
  1627. {
  1628. assert(FFileSystem);
  1629. try
  1630. {
  1631. // reset flag is case we are called externally (like from console dialog)
  1632. FReadCurrentDirectoryPending = false;
  1633. LogEvent("Getting current directory name.");
  1634. AnsiString OldDirectory = FFileSystem->CurrentDirectory;
  1635. FFileSystem->ReadCurrentDirectory();
  1636. ReactOnCommand(fsCurrentDirectory);
  1637. if (SessionData->CacheDirectoryChanges)
  1638. {
  1639. assert(FDirectoryChangesCache != NULL);
  1640. FDirectoryChangesCache->AddDirectoryChange(OldDirectory,
  1641. FLastDirectoryChange, CurrentDirectory);
  1642. // not to broke the cache, if the next directory change would not
  1643. // be initialited by ChangeDirectory(), which sets it
  1644. // (HomeDirectory() particularly)
  1645. FLastDirectoryChange = "";
  1646. }
  1647. if (OldDirectory.IsEmpty())
  1648. {
  1649. FLockDirectory = (SessionData->LockInHome ?
  1650. FFileSystem->CurrentDirectory : AnsiString(""));
  1651. }
  1652. if (OldDirectory != FFileSystem->CurrentDirectory) DoChangeDirectory();
  1653. }
  1654. catch (Exception &E)
  1655. {
  1656. CommandError(&E, LoadStr(READ_CURRENT_DIR_ERROR));
  1657. }
  1658. }
  1659. //---------------------------------------------------------------------------
  1660. void __fastcall TTerminal::ReadDirectory(bool ReloadOnly, bool ForceCache)
  1661. {
  1662. bool LoadedFromCache = false;
  1663. if (SessionData->CacheDirectories && FDirectoryCache->HasFileList(CurrentDirectory))
  1664. {
  1665. if (ReloadOnly && !ForceCache)
  1666. {
  1667. LogEvent("Cached directory not reloaded.");
  1668. }
  1669. else
  1670. {
  1671. DoStartReadDirectory();
  1672. try
  1673. {
  1674. LoadedFromCache = FDirectoryCache->GetFileList(CurrentDirectory, FFiles);
  1675. }
  1676. __finally
  1677. {
  1678. DoReadDirectory(ReloadOnly);
  1679. }
  1680. if (LoadedFromCache)
  1681. {
  1682. LogEvent("Directory content loaded from cache.");
  1683. }
  1684. else
  1685. {
  1686. LogEvent("Cached Directory content has been removed.");
  1687. }
  1688. }
  1689. }
  1690. if (!LoadedFromCache)
  1691. {
  1692. DoStartReadDirectory();
  1693. FReadingCurrentDirectory = true;
  1694. bool Cancel = false; // dummy
  1695. DoReadDirectoryProgress(0, Cancel);
  1696. try
  1697. {
  1698. TRemoteDirectory * Files = new TRemoteDirectory(this);
  1699. try
  1700. {
  1701. Files->Directory = CurrentDirectory;
  1702. CustomReadDirectory(Files);
  1703. }
  1704. __finally
  1705. {
  1706. DoReadDirectoryProgress(-1, Cancel);
  1707. FReadingCurrentDirectory = false;
  1708. delete FFiles;
  1709. FFiles = Files;
  1710. DoReadDirectory(ReloadOnly);
  1711. if (Active)
  1712. {
  1713. if (SessionData->CacheDirectories)
  1714. {
  1715. DirectoryLoaded(FFiles);
  1716. }
  1717. }
  1718. }
  1719. }
  1720. catch (Exception &E)
  1721. {
  1722. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FFiles->Directory))));
  1723. }
  1724. }
  1725. }
  1726. //---------------------------------------------------------------------------
  1727. void __fastcall TTerminal::CustomReadDirectory(TRemoteFileList * FileList)
  1728. {
  1729. assert(FileList);
  1730. assert(FFileSystem);
  1731. FFileSystem->ReadDirectory(FileList);
  1732. ReactOnCommand(fsListDirectory);
  1733. }
  1734. //---------------------------------------------------------------------------
  1735. TRemoteFileList * TTerminal::ReadDirectoryListing(AnsiString Directory, bool UseCache)
  1736. {
  1737. TRemoteFileList * FileList;
  1738. try
  1739. {
  1740. FileList = new TRemoteFileList();
  1741. try
  1742. {
  1743. bool Cache = UseCache && SessionData->CacheDirectories;
  1744. bool LoadedFromCache = Cache && FDirectoryCache->HasFileList(Directory);
  1745. if (LoadedFromCache)
  1746. {
  1747. LoadedFromCache = FDirectoryCache->GetFileList(Directory, FileList);
  1748. }
  1749. if (!LoadedFromCache)
  1750. {
  1751. FileList->Directory = Directory;
  1752. ExceptionOnFail = true;
  1753. try
  1754. {
  1755. ReadDirectory(FileList);
  1756. }
  1757. __finally
  1758. {
  1759. ExceptionOnFail = false;
  1760. }
  1761. if (Cache)
  1762. {
  1763. AddCachedFileList(FileList);
  1764. }
  1765. }
  1766. }
  1767. catch(...)
  1768. {
  1769. delete FileList;
  1770. FileList = NULL;
  1771. throw;
  1772. }
  1773. }
  1774. catch(Exception & E)
  1775. {
  1776. COMMAND_ERROR_ARI
  1777. (
  1778. "",
  1779. FileList = ReadDirectoryListing(Directory, UseCache);
  1780. );
  1781. }
  1782. return FileList;
  1783. }
  1784. //---------------------------------------------------------------------------
  1785. void __fastcall TTerminal::ProcessDirectory(const AnsiString DirName,
  1786. TProcessFileEvent CallBackFunc, void * Param, bool UseCache)
  1787. {
  1788. TRemoteFileList * FileList = ReadDirectoryListing(DirName, UseCache);
  1789. // skip if directory listing fails and user selects "skip"
  1790. if (FileList)
  1791. {
  1792. try
  1793. {
  1794. AnsiString Directory = UnixIncludeTrailingBackslash(DirName);
  1795. TRemoteFile * File;
  1796. for (int Index = 0; Index < FileList->Count; Index++)
  1797. {
  1798. File = FileList->Files[Index];
  1799. if (!File->IsParentDirectory && !File->IsThisDirectory)
  1800. {
  1801. CallBackFunc(Directory + File->FileName, File, Param);
  1802. }
  1803. }
  1804. }
  1805. __finally
  1806. {
  1807. delete FileList;
  1808. }
  1809. }
  1810. }
  1811. //---------------------------------------------------------------------------
  1812. void __fastcall TTerminal::ReadDirectory(TRemoteFileList * FileList)
  1813. {
  1814. try
  1815. {
  1816. CustomReadDirectory(FileList);
  1817. }
  1818. catch (Exception &E)
  1819. {
  1820. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FileList->Directory))));
  1821. }
  1822. }
  1823. //---------------------------------------------------------------------------
  1824. void __fastcall TTerminal::ReadSymlink(TRemoteFile * SymlinkFile,
  1825. TRemoteFile *& File)
  1826. {
  1827. assert(FFileSystem);
  1828. try
  1829. {
  1830. LogEvent(FORMAT("Reading symlink \"%s\".", (SymlinkFile->FileName)));
  1831. FFileSystem->ReadSymlink(SymlinkFile, File);
  1832. ReactOnCommand(fsReadSymlink);
  1833. }
  1834. catch (Exception &E)
  1835. {
  1836. CommandError(&E, FMTLOAD(READ_SYMLINK_ERROR, (SymlinkFile->FileName)));
  1837. }
  1838. }
  1839. //---------------------------------------------------------------------------
  1840. void __fastcall TTerminal::ReadFile(const AnsiString FileName,
  1841. TRemoteFile *& File)
  1842. {
  1843. assert(FFileSystem);
  1844. File = NULL;
  1845. try
  1846. {
  1847. LogEvent(FORMAT("Listing file \"%s\".", (FileName)));
  1848. FFileSystem->ReadFile(FileName, File);
  1849. ReactOnCommand(fsListFile);
  1850. }
  1851. catch (Exception &E)
  1852. {
  1853. if (File) delete File;
  1854. File = NULL;
  1855. CommandError(&E, FMTLOAD(CANT_GET_ATTRS, (FileName)));
  1856. }
  1857. }
  1858. //---------------------------------------------------------------------------
  1859. void __fastcall TTerminal::AnnounceFileListOperation()
  1860. {
  1861. FFileSystem->AnnounceFileListOperation();
  1862. }
  1863. //---------------------------------------------------------------------------
  1864. bool __fastcall TTerminal::ProcessFiles(TStrings * FileList,
  1865. TFileOperation Operation, TProcessFileEvent ProcessFile, void * Param,
  1866. TOperationSide Side, bool Ex)
  1867. {
  1868. assert(FFileSystem);
  1869. assert(FileList);
  1870. bool Result = false;
  1871. bool DisconnectWhenComplete = false;
  1872. try
  1873. {
  1874. TFileOperationProgressType Progress(FOnProgress, FOnFinished);
  1875. Progress.Start(Operation, Side, FileList->Count);
  1876. FOperationProgress = &Progress;
  1877. try
  1878. {
  1879. if (Side == osRemote)
  1880. {
  1881. BeginTransaction();
  1882. }
  1883. try
  1884. {
  1885. int Index = 0;
  1886. AnsiString FileName;
  1887. bool Success;
  1888. while ((Index < FileList->Count) && (Progress.Cancel == csContinue))
  1889. {
  1890. FileName = FileList->Strings[Index];
  1891. try
  1892. {
  1893. Success = false;
  1894. if (!Ex)
  1895. {
  1896. ProcessFile(FileName, (TRemoteFile *)FileList->Objects[Index], Param);
  1897. }
  1898. else
  1899. {
  1900. // not used anymore
  1901. TProcessFileEventEx ProcessFileEx = (TProcessFileEventEx)ProcessFile;
  1902. ProcessFileEx(FileName, (TRemoteFile *)FileList->Objects[Index], Param, Index);
  1903. }
  1904. Success = true;
  1905. }
  1906. __finally
  1907. {
  1908. Progress.Finish(FileName, Success, DisconnectWhenComplete);
  1909. }
  1910. Index++;
  1911. }
  1912. }
  1913. __finally
  1914. {
  1915. if (Side == osRemote)
  1916. {
  1917. EndTransaction();
  1918. }
  1919. }
  1920. if (Progress.Cancel == csContinue)
  1921. {
  1922. Result = true;
  1923. }
  1924. }
  1925. __finally
  1926. {
  1927. FOperationProgress = NULL;
  1928. Progress.Stop();
  1929. }
  1930. }
  1931. catch (...)
  1932. {
  1933. DisconnectWhenComplete = false;
  1934. // this was missing here. was it by purpose?
  1935. // without it any error message is lost
  1936. throw;
  1937. }
  1938. if (DisconnectWhenComplete)
  1939. {
  1940. CloseOnCompletion();
  1941. }
  1942. return Result;
  1943. }
  1944. //---------------------------------------------------------------------------
  1945. // not used anymore
  1946. bool __fastcall TTerminal::ProcessFilesEx(TStrings * FileList, TFileOperation Operation,
  1947. TProcessFileEventEx ProcessFile, void * Param, TOperationSide Side)
  1948. {
  1949. return ProcessFiles(FileList, Operation, TProcessFileEvent(ProcessFile),
  1950. Param, Side, true);
  1951. }
  1952. //---------------------------------------------------------------------------
  1953. TStrings * __fastcall TTerminal::GetFixedPaths()
  1954. {
  1955. assert(FFileSystem != NULL);
  1956. return FFileSystem->GetFixedPaths();
  1957. }
  1958. //---------------------------------------------------------------------------
  1959. bool __fastcall TTerminal::GetResolvingSymlinks()
  1960. {
  1961. return SessionData->ResolveSymlinks && IsCapable[fcResolveSymlink];
  1962. }
  1963. //---------------------------------------------------------------------------
  1964. TUsableCopyParamAttrs __fastcall TTerminal::UsableCopyParamAttrs(int Params)
  1965. {
  1966. TUsableCopyParamAttrs Result;
  1967. Result.General =
  1968. FLAGMASK(!IsCapable[fcTextMode], cpaNoTransferMode) |
  1969. FLAGMASK(!IsCapable[fcModeChanging], cpaNoRights) |
  1970. FLAGMASK(!IsCapable[fcModeChanging], cpaNoPreserveReadOnly) |
  1971. FLAGMASK(FLAGSET(Params, cpDelete), cpaNoExcludeMask) |
  1972. FLAGMASK(FLAGSET(Params, cpDelete), cpaNoClearArchive) |
  1973. FLAGMASK(!IsCapable[fcIgnorePermErrors], cpaNoIgnorePermErrors);
  1974. Result.Download = Result.General | cpaNoClearArchive | cpaNoRights |
  1975. cpaNoIgnorePermErrors;
  1976. Result.Upload = Result.General | cpaNoPreserveReadOnly |
  1977. FLAGMASK(!IsCapable[fcModeChangingUpload], cpaNoRights) |
  1978. FLAGMASK(!IsCapable[fcPreservingTimestampUpload], cpaNoPreserveTime);
  1979. return Result;
  1980. }
  1981. //---------------------------------------------------------------------------
  1982. bool __fastcall TTerminal::IsRecycledFile(AnsiString FileName)
  1983. {
  1984. AnsiString Path = UnixExtractFilePath(FileName);
  1985. if (Path.IsEmpty())
  1986. {
  1987. Path = CurrentDirectory;
  1988. }
  1989. return UnixComparePaths(Path, SessionData->RecycleBinPath);
  1990. }
  1991. //---------------------------------------------------------------------------
  1992. void __fastcall TTerminal::RecycleFile(AnsiString FileName,
  1993. const TRemoteFile * File)
  1994. {
  1995. if (FileName.IsEmpty())
  1996. {
  1997. assert(File != NULL);
  1998. FileName = File->FileName;
  1999. }
  2000. if (!IsRecycledFile(FileName))
  2001. {
  2002. LogEvent(FORMAT("Moving file \"%s\" to remote recycle bin '%s'.",
  2003. (FileName, SessionData->RecycleBinPath)));
  2004. TMoveFileParams Params;
  2005. Params.Target = SessionData->RecycleBinPath;
  2006. Params.FileMask = FORMAT("*-%s.*", (FormatDateTime("yyyymmdd-hhnnss", Now())));
  2007. MoveFile(FileName, File, &Params);
  2008. }
  2009. }
  2010. //---------------------------------------------------------------------------
  2011. void __fastcall TTerminal::DeleteFile(AnsiString FileName,
  2012. const TRemoteFile * File, void * Recursive)
  2013. {
  2014. if (FileName.IsEmpty() && File)
  2015. {
  2016. FileName = File->FileName;
  2017. }
  2018. if (OperationProgress && OperationProgress->Operation == foDelete)
  2019. {
  2020. if (OperationProgress->Cancel != csContinue) Abort();
  2021. OperationProgress->SetFile(FileName);
  2022. }
  2023. if (SessionData->DeleteToRecycleBin && !IsRecycledFile(FileName))
  2024. {
  2025. RecycleFile(FileName, File);
  2026. }
  2027. else
  2028. {
  2029. LogEvent(FORMAT("Deleting file \"%s\".", (FileName)));
  2030. if (File) FileModified(File, FileName, true);
  2031. DoDeleteFile(FileName, File, Recursive);
  2032. ReactOnCommand(fsDeleteFile);
  2033. }
  2034. }
  2035. //---------------------------------------------------------------------------
  2036. void __fastcall TTerminal::DoDeleteFile(const AnsiString FileName,
  2037. const TRemoteFile * File, void * Recursive)
  2038. {
  2039. try
  2040. {
  2041. assert(FFileSystem);
  2042. // 'File' parameter: SFTPFileSystem needs to know if file is file or directory
  2043. FFileSystem->DeleteFile(FileName, File,
  2044. Recursive ? *((bool*)Recursive) : true);
  2045. }
  2046. catch(Exception & E)
  2047. {
  2048. COMMAND_ERROR_ARI
  2049. (
  2050. FMTLOAD(DELETE_FILE_ERROR, (FileName)),
  2051. DoDeleteFile(FileName, File, Recursive)
  2052. );
  2053. }
  2054. }
  2055. //---------------------------------------------------------------------------
  2056. bool __fastcall TTerminal::DeleteFiles(TStrings * FilesToDelete, bool * Recursive)
  2057. {
  2058. // TODO: avoid resolving symlinks while reading subdirectories.
  2059. // Resolving does not work anyway for relative symlinks in subdirectories
  2060. // (at least for SFTP).
  2061. return ProcessFiles(FilesToDelete, foDelete, DeleteFile, Recursive);
  2062. }
  2063. //---------------------------------------------------------------------------
  2064. void __fastcall TTerminal::DeleteLocalFile(AnsiString FileName,
  2065. const TRemoteFile * /*File*/, void * /*Param*/)
  2066. {
  2067. if (OnDeleteLocalFile == NULL)
  2068. {
  2069. if (!RecursiveDeleteFile(FileName, false))
  2070. {
  2071. throw Exception(FMTLOAD(DELETE_FILE_ERROR, (FileName)));
  2072. }
  2073. }
  2074. else
  2075. {
  2076. OnDeleteLocalFile(FileName);
  2077. }
  2078. }
  2079. //---------------------------------------------------------------------------
  2080. bool __fastcall TTerminal::DeleteLocalFiles(TStrings * FileList)
  2081. {
  2082. return ProcessFiles(FileList, foDelete, DeleteLocalFile, NULL, osLocal);
  2083. }
  2084. //---------------------------------------------------------------------------
  2085. void __fastcall TTerminal::CustomCommandOnFile(AnsiString FileName,
  2086. const TRemoteFile * File, void * AParams)
  2087. {
  2088. TCustomCommandParams * Params = ((TCustomCommandParams *)AParams);
  2089. if (FileName.IsEmpty() && File)
  2090. {
  2091. FileName = File->FileName;
  2092. }
  2093. if (OperationProgress && OperationProgress->Operation == foCustomCommand)
  2094. {
  2095. if (OperationProgress->Cancel != csContinue) Abort();
  2096. OperationProgress->SetFile(FileName);
  2097. }
  2098. LogEvent(FORMAT("Executing custom command \"%s\" (%d) on file \"%s\".",
  2099. (Params->Command, Params->Params, FileName)));
  2100. if (File) FileModified(File, FileName);
  2101. DoCustomCommandOnFile(FileName, File, Params->Command, Params->Params,
  2102. Params->OutputEvent);
  2103. ReactOnCommand(fsAnyCommand);
  2104. }
  2105. //---------------------------------------------------------------------------
  2106. void __fastcall TTerminal::DoCustomCommandOnFile(AnsiString FileName,
  2107. const TRemoteFile * File, AnsiString Command, int Params,
  2108. TCaptureOutputEvent OutputEvent)
  2109. {
  2110. try
  2111. {
  2112. if (IsCapable[fcAnyCommand])
  2113. {
  2114. assert(FFileSystem);
  2115. assert(fcShellAnyCommand);
  2116. FFileSystem->CustomCommandOnFile(FileName, File, Command, Params, OutputEvent);
  2117. }
  2118. else
  2119. {
  2120. assert(CommandSessionOpened);
  2121. assert(FCommandSession->FSProtocol == cfsSCP);
  2122. LogEvent("Executing custom command on command session.");
  2123. FCommandSession->CurrentDirectory = CurrentDirectory;
  2124. FCommandSession->FFileSystem->CustomCommandOnFile(FileName, File, Command,
  2125. Params, OutputEvent);
  2126. }
  2127. }
  2128. catch(Exception & E)
  2129. {
  2130. COMMAND_ERROR_ARI
  2131. (
  2132. FMTLOAD(CUSTOM_COMMAND_ERROR, (Command, FileName)),
  2133. DoCustomCommandOnFile(FileName, File, Command, Params, OutputEvent)
  2134. );
  2135. }
  2136. }
  2137. //---------------------------------------------------------------------------
  2138. void __fastcall TTerminal::CustomCommandOnFiles(AnsiString Command,
  2139. int Params, TStrings * Files, TCaptureOutputEvent OutputEvent)
  2140. {
  2141. if (!TRemoteCustomCommand().IsFileListCommand(Command))
  2142. {
  2143. TCustomCommandParams AParams;
  2144. AParams.Command = Command;
  2145. AParams.Params = Params;
  2146. AParams.OutputEvent = OutputEvent;
  2147. ProcessFiles(Files, foCustomCommand, CustomCommandOnFile, &AParams);
  2148. }
  2149. else
  2150. {
  2151. AnsiString FileList;
  2152. for (int i = 0; i < Files->Count; i++)
  2153. {
  2154. TRemoteFile * File = static_cast<TRemoteFile *>(Files->Objects[i]);
  2155. bool Dir = File->IsDirectory && !File->IsSymLink;
  2156. if (!Dir || FLAGSET(Params, ccApplyToDirectories))
  2157. {
  2158. if (!FileList.IsEmpty())
  2159. {
  2160. FileList += " ";
  2161. }
  2162. FileList += "\"" + ShellDelimitStr(Files->Strings[i], '"') + "\"";
  2163. }
  2164. }
  2165. AnsiString Cmd = TRemoteCustomCommand("", FileList).Complete(Command, true);
  2166. AnyCommand(Cmd, OutputEvent);
  2167. }
  2168. }
  2169. //---------------------------------------------------------------------------
  2170. void __fastcall TTerminal::ChangeFileProperties(AnsiString FileName,
  2171. const TRemoteFile * File, /*const TRemoteProperties*/ void * Properties)
  2172. {
  2173. TRemoteProperties * RProperties = (TRemoteProperties *)Properties;
  2174. assert(RProperties && !RProperties->Valid.Empty());
  2175. if (FileName.IsEmpty() && File)
  2176. {
  2177. FileName = File->FileName;
  2178. }
  2179. if (OperationProgress && OperationProgress->Operation == foSetProperties)
  2180. {
  2181. if (OperationProgress->Cancel != csContinue) Abort();
  2182. OperationProgress->SetFile(FileName);
  2183. }
  2184. if (Log->Logging)
  2185. {
  2186. LogEvent(FORMAT("Changing properties of \"%s\" (%s)",
  2187. (FileName, BooleanToEngStr(RProperties->Recursive))));
  2188. if (RProperties->Valid.Contains(vpRights))
  2189. {
  2190. LogEvent(FORMAT(" - mode: \"%s\"", (RProperties->Rights.ModeStr)));
  2191. }
  2192. if (RProperties->Valid.Contains(vpGroup))
  2193. {
  2194. LogEvent(FORMAT(" - group: \"%s\"", (RProperties->Group)));
  2195. }
  2196. if (RProperties->Valid.Contains(vpOwner))
  2197. {
  2198. LogEvent(FORMAT(" - owner: \"%s\"", (RProperties->Owner)));
  2199. }
  2200. if (RProperties->Valid.Contains(vpModification))
  2201. {
  2202. LogEvent(FORMAT(" - modification: \"%s\"",
  2203. (FormatDateTime("dddddd tt",
  2204. UnixToDateTime(RProperties->Modification, SessionData->DSTMode)))));
  2205. }
  2206. if (RProperties->Valid.Contains(vpLastAccess))
  2207. {
  2208. LogEvent(FORMAT(" - last access: \"%s\"",
  2209. (FormatDateTime("dddddd tt",
  2210. UnixToDateTime(RProperties->LastAccess, SessionData->DSTMode)))));
  2211. }
  2212. }
  2213. FileModified(File, FileName);
  2214. DoChangeFileProperties(FileName, File, RProperties);
  2215. ReactOnCommand(fsChangeProperties);
  2216. }
  2217. //---------------------------------------------------------------------------
  2218. void __fastcall TTerminal::DoChangeFileProperties(const AnsiString FileName,
  2219. const TRemoteFile * File, const TRemoteProperties * Properties)
  2220. {
  2221. try
  2222. {
  2223. assert(FFileSystem);
  2224. FFileSystem->ChangeFileProperties(FileName, File, Properties);
  2225. }
  2226. catch(Exception & E)
  2227. {
  2228. COMMAND_ERROR_ARI
  2229. (
  2230. FMTLOAD(CHANGE_PROPERTIES_ERROR, (FileName)),
  2231. DoChangeFileProperties(FileName, File, Properties)
  2232. );
  2233. }
  2234. }
  2235. //---------------------------------------------------------------------------
  2236. void __fastcall TTerminal::ChangeFilesProperties(TStrings * FileList,
  2237. const TRemoteProperties * Properties)
  2238. {
  2239. AnnounceFileListOperation();
  2240. ProcessFiles(FileList, foSetProperties, ChangeFileProperties, (void *)Properties);
  2241. }
  2242. //---------------------------------------------------------------------------
  2243. bool __fastcall TTerminal::LoadFilesProperties(TStrings * FileList)
  2244. {
  2245. bool Result =
  2246. IsCapable[fcLoadingAdditionalProperties] &&
  2247. FFileSystem->LoadFilesProperties(FileList);
  2248. if (Result && SessionData->CacheDirectories &&
  2249. (FileList->Count > 0) &&
  2250. (dynamic_cast<TRemoteFile *>(FileList->Objects[0])->Directory == FFiles))
  2251. {
  2252. AddCachedFileList(FFiles);
  2253. }
  2254. return Result;
  2255. }
  2256. //---------------------------------------------------------------------------
  2257. void __fastcall TTerminal::CalculateFileSize(AnsiString FileName,
  2258. const TRemoteFile * File, /*TCalculateSizeParams*/ void * Param)
  2259. {
  2260. assert(Param);
  2261. assert(File);
  2262. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Param);
  2263. if (FileName.IsEmpty())
  2264. {
  2265. FileName = File->FileName;
  2266. }
  2267. bool AllowTransfer = (AParams->CopyParam == NULL);
  2268. if (!AllowTransfer)
  2269. {
  2270. TFileMasks::TParams MaskParams;
  2271. MaskParams.Size = File->Size;
  2272. AllowTransfer = AParams->CopyParam->AllowTransfer(
  2273. UnixExcludeTrailingBackslash(File->FullFileName), osRemote, File->IsDirectory,
  2274. MaskParams);
  2275. }
  2276. if (AllowTransfer)
  2277. {
  2278. if (File->IsDirectory)
  2279. {
  2280. if (!File->IsSymLink)
  2281. {
  2282. LogEvent(FORMAT("Getting size of directory \"%s\"", (FileName)));
  2283. // pass in full path so we get it back in file list for AllowTransfer() exclusion
  2284. DoCalculateDirectorySize(File->FullFileName, File, AParams);
  2285. }
  2286. else
  2287. {
  2288. AParams->Size += File->Size;
  2289. }
  2290. if (AParams->Stats != NULL)
  2291. {
  2292. AParams->Stats->Directories++;
  2293. }
  2294. }
  2295. else
  2296. {
  2297. AParams->Size += File->Size;
  2298. if (AParams->Stats != NULL)
  2299. {
  2300. AParams->Stats->Files++;
  2301. }
  2302. }
  2303. if ((AParams->Stats != NULL) && File->IsSymLink)
  2304. {
  2305. AParams->Stats->SymLinks++;
  2306. }
  2307. }
  2308. if (OperationProgress && OperationProgress->Operation == foCalculateSize)
  2309. {
  2310. if (OperationProgress->Cancel != csContinue) Abort();
  2311. OperationProgress->SetFile(FileName);
  2312. }
  2313. }
  2314. //---------------------------------------------------------------------------
  2315. void __fastcall TTerminal::DoCalculateDirectorySize(const AnsiString FileName,
  2316. const TRemoteFile * File, TCalculateSizeParams * Params)
  2317. {
  2318. try
  2319. {
  2320. ProcessDirectory(FileName, CalculateFileSize, Params);
  2321. }
  2322. catch(Exception & E)
  2323. {
  2324. if (!Active || ((Params->Params & csIgnoreErrors) == 0))
  2325. {
  2326. COMMAND_ERROR_ARI
  2327. (
  2328. FMTLOAD(CALCULATE_SIZE_ERROR, (FileName)),
  2329. DoCalculateDirectorySize(FileName, File, Params)
  2330. );
  2331. }
  2332. }
  2333. }
  2334. //---------------------------------------------------------------------------
  2335. void __fastcall TTerminal::CalculateFilesSize(TStrings * FileList,
  2336. __int64 & Size, int Params, const TCopyParamType * CopyParam,
  2337. TCalculateSizeStats * Stats)
  2338. {
  2339. TCalculateSizeParams Param;
  2340. Param.Size = 0;
  2341. Param.Params = Params;
  2342. Param.CopyParam = CopyParam;
  2343. Param.Stats = Stats;
  2344. ProcessFiles(FileList, foCalculateSize, CalculateFileSize, &Param);
  2345. Size = Param.Size;
  2346. }
  2347. //---------------------------------------------------------------------------
  2348. void __fastcall TTerminal::CalculateFilesChecksum(const AnsiString & Alg,
  2349. TStrings * FileList, TStrings * Checksums,
  2350. TCalculatedChecksumEvent OnCalculatedChecksum)
  2351. {
  2352. FFileSystem->CalculateFilesChecksum(Alg, FileList, Checksums, OnCalculatedChecksum);
  2353. }
  2354. //---------------------------------------------------------------------------
  2355. void __fastcall TTerminal::RenameFile(const AnsiString FileName,
  2356. const AnsiString NewName)
  2357. {
  2358. LogEvent(FORMAT("Renaming file \"%s\" to \"%s\".", (FileName, NewName)));
  2359. DoRenameFile(FileName, NewName, false);
  2360. ReactOnCommand(fsRenameFile);
  2361. }
  2362. //---------------------------------------------------------------------------
  2363. void __fastcall TTerminal::RenameFile(const TRemoteFile * File,
  2364. const AnsiString NewName, bool CheckExistence)
  2365. {
  2366. assert(File && File->Directory == FFiles);
  2367. bool Proceed = true;
  2368. // if filename doesn't contain path, we check for existence of file
  2369. if ((File->FileName != NewName) && CheckExistence &&
  2370. Configuration->ConfirmOverwriting &&
  2371. UnixComparePaths(CurrentDirectory, FFiles->Directory))
  2372. {
  2373. TRemoteFile * DuplicateFile = FFiles->FindFile(NewName);
  2374. if (DuplicateFile)
  2375. {
  2376. AnsiString QuestionFmt;
  2377. if (DuplicateFile->IsDirectory) QuestionFmt = LoadStr(DIRECTORY_OVERWRITE);
  2378. else QuestionFmt = LoadStr(FILE_OVERWRITE);
  2379. int Result;
  2380. TQueryParams Params(qpNeverAskAgainCheck);
  2381. Result = QueryUser(FORMAT(QuestionFmt, (NewName)), NULL,
  2382. qaYes | qaNo, &Params);
  2383. if (Result == qaNeverAskAgain)
  2384. {
  2385. Proceed = true;
  2386. Configuration->ConfirmOverwriting = false;
  2387. }
  2388. else
  2389. {
  2390. Proceed = (Result == qaYes);
  2391. }
  2392. }
  2393. }
  2394. if (Proceed)
  2395. {
  2396. FileModified(File, File->FileName);
  2397. RenameFile(File->FileName, NewName);
  2398. }
  2399. }
  2400. //---------------------------------------------------------------------------
  2401. void __fastcall TTerminal::DoRenameFile(const AnsiString FileName,
  2402. const AnsiString NewName, bool Move)
  2403. {
  2404. try
  2405. {
  2406. assert(FFileSystem);
  2407. FFileSystem->RenameFile(FileName, NewName);
  2408. }
  2409. catch(Exception & E)
  2410. {
  2411. COMMAND_ERROR_ARI
  2412. (
  2413. FMTLOAD(Move ? MOVE_FILE_ERROR : RENAME_FILE_ERROR, (FileName, NewName)),
  2414. DoRenameFile(FileName, NewName, Move)
  2415. );
  2416. }
  2417. }
  2418. //---------------------------------------------------------------------------
  2419. void __fastcall TTerminal::MoveFile(const AnsiString FileName,
  2420. const TRemoteFile * File, /*const TMoveFileParams*/ void * Param)
  2421. {
  2422. if (OperationProgress &&
  2423. ((OperationProgress->Operation == foRemoteMove) ||
  2424. (OperationProgress->Operation == foDelete)))
  2425. {
  2426. if (OperationProgress->Cancel != csContinue) Abort();
  2427. OperationProgress->SetFile(FileName);
  2428. }
  2429. assert(Param != NULL);
  2430. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  2431. AnsiString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  2432. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  2433. LogEvent(FORMAT("Moving file \"%s\" to \"%s\".", (FileName, NewName)));
  2434. FileModified(File, FileName);
  2435. DoRenameFile(FileName, NewName, true);
  2436. ReactOnCommand(fsMoveFile);
  2437. }
  2438. //---------------------------------------------------------------------------
  2439. bool __fastcall TTerminal::MoveFiles(TStrings * FileList, const AnsiString Target,
  2440. const AnsiString FileMask)
  2441. {
  2442. TMoveFileParams Params;
  2443. Params.Target = Target;
  2444. Params.FileMask = FileMask;
  2445. DirectoryModified(Target, true);
  2446. return ProcessFiles(FileList, foRemoteMove, MoveFile, &Params);
  2447. }
  2448. //---------------------------------------------------------------------------
  2449. void __fastcall TTerminal::DoCopyFile(const AnsiString FileName,
  2450. const AnsiString NewName)
  2451. {
  2452. try
  2453. {
  2454. assert(FFileSystem);
  2455. if (IsCapable[fcRemoteCopy])
  2456. {
  2457. FFileSystem->CopyFile(FileName, NewName);
  2458. }
  2459. else
  2460. {
  2461. assert(CommandSessionOpened);
  2462. assert(FCommandSession->FSProtocol == cfsSCP);
  2463. LogEvent("Copying file on command session.");
  2464. FCommandSession->CurrentDirectory = CurrentDirectory;
  2465. FCommandSession->FFileSystem->CopyFile(FileName, NewName);
  2466. }
  2467. }
  2468. catch(Exception & E)
  2469. {
  2470. COMMAND_ERROR_ARI
  2471. (
  2472. FMTLOAD(COPY_FILE_ERROR, (FileName, NewName)),
  2473. DoCopyFile(FileName, NewName)
  2474. );
  2475. }
  2476. }
  2477. //---------------------------------------------------------------------------
  2478. void __fastcall TTerminal::CopyFile(const AnsiString FileName,
  2479. const TRemoteFile * /*File*/, /*const TMoveFileParams*/ void * Param)
  2480. {
  2481. if (OperationProgress && (OperationProgress->Operation == foRemoteCopy))
  2482. {
  2483. if (OperationProgress->Cancel != csContinue) Abort();
  2484. OperationProgress->SetFile(FileName);
  2485. }
  2486. assert(Param != NULL);
  2487. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  2488. AnsiString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  2489. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  2490. LogEvent(FORMAT("Copying file \"%s\" to \"%s\".", (FileName, NewName)));
  2491. DoCopyFile(FileName, NewName);
  2492. ReactOnCommand(fsCopyFile);
  2493. }
  2494. //---------------------------------------------------------------------------
  2495. bool __fastcall TTerminal::CopyFiles(TStrings * FileList, const AnsiString Target,
  2496. const AnsiString FileMask)
  2497. {
  2498. TMoveFileParams Params;
  2499. Params.Target = Target;
  2500. Params.FileMask = FileMask;
  2501. DirectoryModified(Target, true);
  2502. return ProcessFiles(FileList, foRemoteCopy, CopyFile, &Params);
  2503. }
  2504. //---------------------------------------------------------------------------
  2505. void __fastcall TTerminal::CreateDirectory(const AnsiString DirName,
  2506. const TRemoteProperties * Properties)
  2507. {
  2508. assert(FFileSystem);
  2509. EnsureNonExistence(DirName);
  2510. FileModified(NULL, DirName);
  2511. LogEvent(FORMAT("Creating directory \"%s\".", (DirName)));
  2512. DoCreateDirectory(DirName, Properties);
  2513. ReactOnCommand(fsCreateDirectory);
  2514. }
  2515. //---------------------------------------------------------------------------
  2516. void __fastcall TTerminal::DoCreateDirectory(const AnsiString DirName,
  2517. const TRemoteProperties * Properties)
  2518. {
  2519. try
  2520. {
  2521. assert(FFileSystem);
  2522. FFileSystem->CreateDirectory(DirName, Properties);
  2523. }
  2524. catch(Exception & E)
  2525. {
  2526. COMMAND_ERROR_ARI
  2527. (
  2528. FMTLOAD(CREATE_DIR_ERROR, (DirName)),
  2529. DoCreateDirectory(DirName, Properties)
  2530. );
  2531. }
  2532. }
  2533. //---------------------------------------------------------------------------
  2534. void __fastcall TTerminal::CreateLink(const AnsiString FileName,
  2535. const AnsiString PointTo, bool Symbolic)
  2536. {
  2537. assert(FFileSystem);
  2538. EnsureNonExistence(FileName);
  2539. if (SessionData->CacheDirectories)
  2540. {
  2541. DirectoryModified(CurrentDirectory, false);
  2542. }
  2543. LogEvent(FORMAT("Creating link \"%s\" to \"%s\" (symbolic: %s).",
  2544. (FileName, PointTo, BooleanToEngStr(Symbolic))));
  2545. DoCreateLink(FileName, PointTo, Symbolic);
  2546. ReactOnCommand(fsCreateDirectory);
  2547. }
  2548. //---------------------------------------------------------------------------
  2549. void __fastcall TTerminal::DoCreateLink(const AnsiString FileName,
  2550. const AnsiString PointTo, bool Symbolic)
  2551. {
  2552. try
  2553. {
  2554. assert(FFileSystem);
  2555. FFileSystem->CreateLink(FileName, PointTo, Symbolic);
  2556. }
  2557. catch(Exception & E)
  2558. {
  2559. COMMAND_ERROR_ARI
  2560. (
  2561. FMTLOAD(CREATE_LINK_ERROR, (FileName)),
  2562. DoCreateLink(FileName, PointTo, Symbolic);
  2563. );
  2564. }
  2565. }
  2566. //---------------------------------------------------------------------------
  2567. void __fastcall TTerminal::HomeDirectory()
  2568. {
  2569. assert(FFileSystem);
  2570. try
  2571. {
  2572. LogEvent("Changing directory to home directory.");
  2573. FFileSystem->HomeDirectory();
  2574. ReactOnCommand(fsHomeDirectory);
  2575. }
  2576. catch (Exception &E)
  2577. {
  2578. CommandError(&E, LoadStr(CHANGE_HOMEDIR_ERROR));
  2579. }
  2580. }
  2581. //---------------------------------------------------------------------------
  2582. void __fastcall TTerminal::ChangeDirectory(const AnsiString Directory)
  2583. {
  2584. assert(FFileSystem);
  2585. try
  2586. {
  2587. AnsiString CachedDirectory;
  2588. assert(!SessionData->CacheDirectoryChanges || (FDirectoryChangesCache != NULL));
  2589. // never use directory change cache during startup, this ensures, we never
  2590. // end-up initially in non-existing directory
  2591. if ((Status == ssOpened) &&
  2592. SessionData->CacheDirectoryChanges &&
  2593. FDirectoryChangesCache->GetDirectoryChange(PeekCurrentDirectory(),
  2594. Directory, CachedDirectory))
  2595. {
  2596. LogEvent(FORMAT("Cached directory change via \"%s\" to \"%s\".",
  2597. (Directory, CachedDirectory)));
  2598. FFileSystem->CachedChangeDirectory(CachedDirectory);
  2599. }
  2600. else
  2601. {
  2602. LogEvent(FORMAT("Changing directory to \"%s\".", (Directory)));
  2603. FFileSystem->ChangeDirectory(Directory);
  2604. }
  2605. FLastDirectoryChange = Directory;
  2606. ReactOnCommand(fsChangeDirectory);
  2607. }
  2608. catch (Exception &E)
  2609. {
  2610. CommandError(&E, FMTLOAD(CHANGE_DIR_ERROR, (Directory)));
  2611. }
  2612. }
  2613. //---------------------------------------------------------------------------
  2614. void __fastcall TTerminal::LookupUsersGroups()
  2615. {
  2616. assert(FFileSystem);
  2617. assert(IsCapable[fcUserGroupListing]);
  2618. try
  2619. {
  2620. FUsersGroupsLookedup = true;
  2621. LogEvent("Looking up groups and users.");
  2622. FFileSystem->LookupUsersGroups();
  2623. ReactOnCommand(fsLookupUsersGroups);
  2624. if (Log->Logging)
  2625. {
  2626. if (FGroups->Count > 0)
  2627. {
  2628. LogEvent("Following groups found:");
  2629. for (int Index = 0; Index < FGroups->Count; Index++)
  2630. {
  2631. LogEvent(AnsiString(" ") + FGroups->Strings[Index]);
  2632. }
  2633. }
  2634. else
  2635. {
  2636. LogEvent("No groups found.");
  2637. }
  2638. if (FUsers->Count > 0)
  2639. {
  2640. LogEvent("Following users found:");
  2641. for (int Index = 0; Index < FUsers->Count; Index++)
  2642. {
  2643. LogEvent(AnsiString(" ") + FUsers->Strings[Index]);
  2644. }
  2645. }
  2646. else
  2647. {
  2648. LogEvent("No users found.");
  2649. }
  2650. }
  2651. }
  2652. catch (Exception &E)
  2653. {
  2654. CommandError(&E, LoadStr(LOOKUP_GROUPS_ERROR));
  2655. }
  2656. }
  2657. //---------------------------------------------------------------------------
  2658. bool __fastcall TTerminal::AllowedAnyCommand(const AnsiString Command)
  2659. {
  2660. return !Command.Trim().IsEmpty();
  2661. }
  2662. //---------------------------------------------------------------------------
  2663. bool __fastcall TTerminal::GetCommandSessionOpened()
  2664. {
  2665. // consider secodary terminal open in "ready" state only
  2666. // so we never do keepalives on it until it is completelly initialised
  2667. return (FCommandSession != NULL) &&
  2668. (FCommandSession->Status == ssOpened);
  2669. }
  2670. //---------------------------------------------------------------------------
  2671. TTerminal * __fastcall TTerminal::GetCommandSession()
  2672. {
  2673. if ((FCommandSession != NULL) && !FCommandSession->Active)
  2674. {
  2675. SAFE_DESTROY(FCommandSession);
  2676. }
  2677. if (FCommandSession == NULL)
  2678. {
  2679. // transaction cannot be started yet to allow proper matching transation
  2680. // levels between main and command session
  2681. assert(!FInTransaction);
  2682. try
  2683. {
  2684. FCommandSession = new TSecondaryTerminal(this, SessionData,
  2685. Configuration, "Shell");
  2686. FCommandSession->AutoReadDirectory = false;
  2687. FCommandSession->FSessionData->RemoteDirectory = CurrentDirectory;
  2688. FCommandSession->FSessionData->FSProtocol = fsSCPonly;
  2689. FCommandSession->FExceptionOnFail = FExceptionOnFail;
  2690. FCommandSession->OnQueryUser = OnQueryUser;
  2691. FCommandSession->OnPromptUser = OnPromptUser;
  2692. FCommandSession->OnShowExtendedException = OnShowExtendedException;
  2693. FCommandSession->OnProgress = OnProgress;
  2694. FCommandSession->OnFinished = OnFinished;
  2695. FCommandSession->OnInformation = OnInformation;
  2696. // do not copy OnDisplayBanner to avoid it being displayed
  2697. }
  2698. catch(...)
  2699. {
  2700. SAFE_DESTROY(FCommandSession);
  2701. throw;
  2702. }
  2703. }
  2704. return FCommandSession;
  2705. }
  2706. //---------------------------------------------------------------------------
  2707. void __fastcall TTerminal::AnyCommand(const AnsiString Command,
  2708. TCaptureOutputEvent OutputEvent)
  2709. {
  2710. assert(FFileSystem);
  2711. try
  2712. {
  2713. DirectoryModified(CurrentDirectory, false);
  2714. if (IsCapable[fcAnyCommand])
  2715. {
  2716. LogEvent("Executing user defined command.");
  2717. FFileSystem->AnyCommand(Command, OutputEvent);
  2718. }
  2719. else
  2720. {
  2721. assert(CommandSessionOpened);
  2722. assert(FCommandSession->FSProtocol == cfsSCP);
  2723. LogEvent("Executing user defined command on command session.");
  2724. FCommandSession->CurrentDirectory = CurrentDirectory;
  2725. FCommandSession->FFileSystem->AnyCommand(Command, OutputEvent);
  2726. FCommandSession->FFileSystem->ReadCurrentDirectory();
  2727. // synchronize pwd (by purpose we lose transaction optimalisation here)
  2728. ChangeDirectory(FCommandSession->CurrentDirectory);
  2729. }
  2730. ReactOnCommand(fsAnyCommand);
  2731. }
  2732. catch (Exception &E)
  2733. {
  2734. if (ExceptionOnFail || (E.InheritsFrom(__classid(EFatal)))) throw;
  2735. else ShowExtendedException(&E);
  2736. }
  2737. }
  2738. //---------------------------------------------------------------------------
  2739. bool __fastcall TTerminal::CreateLocalFile(const AnsiString FileName,
  2740. TFileOperationProgressType * OperationProgress, HANDLE * AHandle,
  2741. bool NoConfirmation)
  2742. {
  2743. assert(AHandle);
  2744. bool Result = true;
  2745. FILE_OPERATION_LOOP (FMTLOAD(CREATE_FILE_ERROR, (FileName)),
  2746. bool Done;
  2747. unsigned int CreateAttr = FILE_ATTRIBUTE_NORMAL;
  2748. do
  2749. {
  2750. *AHandle = CreateFile(FileName.c_str(), GENERIC_WRITE, FILE_SHARE_READ,
  2751. NULL, CREATE_ALWAYS, CreateAttr, 0);
  2752. Done = (*AHandle != INVALID_HANDLE_VALUE);
  2753. if (!Done)
  2754. {
  2755. int FileAttr;
  2756. if (FileExists(FileName) &&
  2757. (((FileAttr = FileGetAttr(FileName)) & (faReadOnly | faHidden)) != 0))
  2758. {
  2759. if (FLAGSET(FileAttr, faReadOnly))
  2760. {
  2761. if (OperationProgress->NoToAll)
  2762. {
  2763. Result = false;
  2764. }
  2765. else if (!OperationProgress->YesToAll && !NoConfirmation)
  2766. {
  2767. int Answer;
  2768. SUSPEND_OPERATION
  2769. (
  2770. Answer = QueryUser(
  2771. FMTLOAD(READ_ONLY_OVERWRITE, (FileName)), NULL,
  2772. qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll, 0);
  2773. );
  2774. switch (Answer) {
  2775. case qaYesToAll: OperationProgress->YesToAll = true; break;
  2776. case qaCancel: OperationProgress->Cancel = csCancel; // continue on next case
  2777. case qaNoToAll: OperationProgress->NoToAll = true;
  2778. case qaNo: Result = false; break;
  2779. }
  2780. }
  2781. }
  2782. else
  2783. {
  2784. assert(FLAGSET(FileAttr, faHidden));
  2785. Result = true;
  2786. }
  2787. if (Result)
  2788. {
  2789. CreateAttr |=
  2790. FLAGMASK(FLAGSET(FileAttr, faHidden), FILE_ATTRIBUTE_HIDDEN) |
  2791. FLAGMASK(FLAGSET(FileAttr, faReadOnly), FILE_ATTRIBUTE_READONLY);
  2792. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (FileName)),
  2793. if (FileSetAttr(FileName, FileAttr & ~(faReadOnly | faHidden)) != 0)
  2794. {
  2795. EXCEPTION;
  2796. }
  2797. );
  2798. }
  2799. else
  2800. {
  2801. Done = true;
  2802. }
  2803. }
  2804. else
  2805. {
  2806. EXCEPTION;
  2807. }
  2808. }
  2809. }
  2810. while (!Done);
  2811. );
  2812. return Result;
  2813. }
  2814. //---------------------------------------------------------------------------
  2815. void __fastcall TTerminal::OpenLocalFile(const AnsiString FileName,
  2816. int Access, int * AAttrs, HANDLE * AHandle, __int64 * ACTime,
  2817. __int64 * AMTime, __int64 * AATime, __int64 * ASize,
  2818. bool TryWriteReadOnly)
  2819. {
  2820. int Attrs = 0;
  2821. HANDLE Handle = 0;
  2822. FILE_OPERATION_LOOP (FMTLOAD(FILE_NOT_EXISTS, (FileName)),
  2823. Attrs = FileGetAttr(FileName);
  2824. if (Attrs == -1) EXCEPTION;
  2825. )
  2826. if ((Attrs & faDirectory) == 0)
  2827. {
  2828. bool NoHandle = false;
  2829. if (!TryWriteReadOnly && (Access == GENERIC_WRITE) &&
  2830. ((Attrs & faReadOnly) != 0))
  2831. {
  2832. Access = GENERIC_READ;
  2833. NoHandle = true;
  2834. }
  2835. FILE_OPERATION_LOOP (FMTLOAD(OPENFILE_ERROR, (FileName)),
  2836. Handle = CreateFile(FileName.c_str(), Access,
  2837. Access == GENERIC_READ ? FILE_SHARE_READ | FILE_SHARE_WRITE : FILE_SHARE_READ,
  2838. NULL, OPEN_EXISTING, 0, 0);
  2839. if (Handle == INVALID_HANDLE_VALUE)
  2840. {
  2841. Handle = 0;
  2842. EXCEPTION;
  2843. }
  2844. );
  2845. try
  2846. {
  2847. if (AATime || AMTime || ACTime)
  2848. {
  2849. // Get last file access and modification time
  2850. FILE_OPERATION_LOOP (FMTLOAD(CANT_GET_ATTRS, (FileName)),
  2851. FILETIME ATime;
  2852. FILETIME MTime;
  2853. FILETIME CTime;
  2854. if (!GetFileTime(Handle, &CTime, &ATime, &MTime)) EXCEPTION;
  2855. if (ACTime)
  2856. {
  2857. *ACTime = ConvertTimestampToUnixSafe(CTime, SessionData->DSTMode);
  2858. }
  2859. if (AATime)
  2860. {
  2861. *AATime = ConvertTimestampToUnixSafe(ATime, SessionData->DSTMode);
  2862. }
  2863. if (AMTime)
  2864. {
  2865. *AMTime = ConvertTimestampToUnix(MTime, SessionData->DSTMode);
  2866. }
  2867. );
  2868. }
  2869. if (ASize)
  2870. {
  2871. // Get file size
  2872. FILE_OPERATION_LOOP (FMTLOAD(CANT_GET_ATTRS, (FileName)),
  2873. unsigned long LSize;
  2874. unsigned long HSize;
  2875. LSize = GetFileSize(Handle, &HSize);
  2876. if ((LSize == 0xFFFFFFFF) && (GetLastError() != NO_ERROR)) EXCEPTION;
  2877. *ASize = (__int64(HSize) << 32) + LSize;
  2878. );
  2879. }
  2880. if ((AHandle == NULL) || NoHandle)
  2881. {
  2882. CloseHandle(Handle);
  2883. Handle = NULL;
  2884. }
  2885. }
  2886. catch(...)
  2887. {
  2888. CloseHandle(Handle);
  2889. throw;
  2890. }
  2891. }
  2892. if (AAttrs) *AAttrs = Attrs;
  2893. if (AHandle) *AHandle = Handle;
  2894. }
  2895. //---------------------------------------------------------------------------
  2896. AnsiString __fastcall TTerminal::FileUrl(const AnsiString Protocol,
  2897. const AnsiString FileName)
  2898. {
  2899. assert(FileName.Length() > 0);
  2900. return Protocol + "://" + EncodeUrlChars(SessionData->SessionName) +
  2901. (FileName[1] == '/' ? "" : "/") + EncodeUrlChars(FileName, "/");
  2902. }
  2903. //---------------------------------------------------------------------------
  2904. AnsiString __fastcall TTerminal::FileUrl(const AnsiString FileName)
  2905. {
  2906. return FFileSystem->FileUrl(FileName);
  2907. }
  2908. //---------------------------------------------------------------------------
  2909. void __fastcall TTerminal::MakeLocalFileList(const AnsiString FileName,
  2910. const TSearchRec Rec, void * Param)
  2911. {
  2912. TMakeLocalFileListParams & Params = *static_cast<TMakeLocalFileListParams*>(Param);
  2913. bool Directory = FLAGSET(Rec.Attr, faDirectory);
  2914. if (Directory && Params.Recursive)
  2915. {
  2916. ProcessLocalDirectory(FileName, MakeLocalFileList, &Params);
  2917. }
  2918. if (!Directory || Params.IncludeDirs)
  2919. {
  2920. Params.FileList->Add(FileName);
  2921. }
  2922. }
  2923. //---------------------------------------------------------------------------
  2924. void __fastcall TTerminal::CalculateLocalFileSize(const AnsiString FileName,
  2925. const TSearchRec Rec, /*TCalculateSizeParams*/ void * Params)
  2926. {
  2927. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Params);
  2928. bool Dir = FLAGSET(Rec.Attr, faDirectory);
  2929. bool AllowTransfer = (AParams->CopyParam == NULL);
  2930. __int64 Size =
  2931. (static_cast<__int64>(Rec.FindData.nFileSizeHigh) << 32) +
  2932. Rec.FindData.nFileSizeLow;
  2933. if (!AllowTransfer)
  2934. {
  2935. TFileMasks::TParams MaskParams;
  2936. MaskParams.Size = Size;
  2937. AllowTransfer = AParams->CopyParam->AllowTransfer(FileName, osLocal, Dir, MaskParams);
  2938. }
  2939. if (AllowTransfer)
  2940. {
  2941. if (!Dir)
  2942. {
  2943. AParams->Size += Size;
  2944. }
  2945. else
  2946. {
  2947. ProcessLocalDirectory(FileName, CalculateLocalFileSize, Params);
  2948. }
  2949. }
  2950. if (OperationProgress && OperationProgress->Operation == foCalculateSize)
  2951. {
  2952. if (OperationProgress->Cancel != csContinue) Abort();
  2953. OperationProgress->SetFile(FileName);
  2954. }
  2955. }
  2956. //---------------------------------------------------------------------------
  2957. void __fastcall TTerminal::CalculateLocalFilesSize(TStrings * FileList,
  2958. __int64 & Size, const TCopyParamType * CopyParam)
  2959. {
  2960. TFileOperationProgressType OperationProgress(FOnProgress, FOnFinished);
  2961. bool DisconnectWhenComplete = false;
  2962. OperationProgress.Start(foCalculateSize, osLocal, FileList->Count);
  2963. try
  2964. {
  2965. TCalculateSizeParams Params;
  2966. Params.Size = 0;
  2967. Params.Params = 0;
  2968. Params.CopyParam = CopyParam;
  2969. assert(!FOperationProgress);
  2970. FOperationProgress = &OperationProgress;
  2971. TSearchRec Rec;
  2972. for (int Index = 0; Index < FileList->Count; Index++)
  2973. {
  2974. AnsiString FileName = FileList->Strings[Index];
  2975. if (FileSearchRec(FileName, Rec))
  2976. {
  2977. CalculateLocalFileSize(FileName, Rec, &Params);
  2978. OperationProgress.Finish(FileName, true, DisconnectWhenComplete);
  2979. }
  2980. }
  2981. Size = Params.Size;
  2982. }
  2983. __finally
  2984. {
  2985. FOperationProgress = NULL;
  2986. OperationProgress.Stop();
  2987. }
  2988. if (DisconnectWhenComplete)
  2989. {
  2990. CloseOnCompletion();
  2991. }
  2992. }
  2993. //---------------------------------------------------------------------------
  2994. struct TSynchronizeFileData
  2995. {
  2996. bool Modified;
  2997. bool New;
  2998. bool IsDirectory;
  2999. TSynchronizeChecklist::TItem::TFileInfo Info;
  3000. TSynchronizeChecklist::TItem::TFileInfo MatchingRemoteFile;
  3001. int MatchingRemoteFileImageIndex;
  3002. FILETIME LocalLastWriteTime;
  3003. };
  3004. //---------------------------------------------------------------------------
  3005. const int sfFirstLevel = 0x01;
  3006. struct TSynchronizeData
  3007. {
  3008. AnsiString LocalDirectory;
  3009. AnsiString RemoteDirectory;
  3010. TTerminal::TSynchronizeMode Mode;
  3011. int Params;
  3012. TSynchronizeDirectory OnSynchronizeDirectory;
  3013. TSynchronizeOptions * Options;
  3014. int Flags;
  3015. TStringList * LocalFileList;
  3016. const TCopyParamType * CopyParam;
  3017. TSynchronizeChecklist * Checklist;
  3018. };
  3019. //---------------------------------------------------------------------------
  3020. TSynchronizeChecklist * __fastcall TTerminal::SynchronizeCollect(const AnsiString LocalDirectory,
  3021. const AnsiString RemoteDirectory, TSynchronizeMode Mode,
  3022. const TCopyParamType * CopyParam, int Params,
  3023. TSynchronizeDirectory OnSynchronizeDirectory,
  3024. TSynchronizeOptions * Options)
  3025. {
  3026. TSynchronizeChecklist * Checklist = new TSynchronizeChecklist();
  3027. try
  3028. {
  3029. DoSynchronizeCollectDirectory(LocalDirectory, RemoteDirectory, Mode,
  3030. CopyParam, Params, OnSynchronizeDirectory, Options, sfFirstLevel,
  3031. Checklist);
  3032. Checklist->Sort();
  3033. }
  3034. catch(...)
  3035. {
  3036. delete Checklist;
  3037. throw;
  3038. }
  3039. return Checklist;
  3040. }
  3041. //---------------------------------------------------------------------------
  3042. void __fastcall TTerminal::DoSynchronizeCollectDirectory(const AnsiString LocalDirectory,
  3043. const AnsiString RemoteDirectory, TSynchronizeMode Mode,
  3044. const TCopyParamType * CopyParam, int Params,
  3045. TSynchronizeDirectory OnSynchronizeDirectory, TSynchronizeOptions * Options,
  3046. int Flags, TSynchronizeChecklist * Checklist)
  3047. {
  3048. TSynchronizeData Data;
  3049. Data.LocalDirectory = IncludeTrailingBackslash(LocalDirectory);
  3050. Data.RemoteDirectory = UnixIncludeTrailingBackslash(RemoteDirectory);
  3051. Data.Mode = Mode;
  3052. Data.Params = Params;
  3053. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  3054. Data.LocalFileList = NULL;
  3055. Data.CopyParam = CopyParam;
  3056. Data.Options = Options;
  3057. Data.Flags = Flags;
  3058. Data.Checklist = Checklist;
  3059. LogEvent(FORMAT("Collecting synchronization list for local directory '%s' and remote directory '%s', "
  3060. "mode = %d, params = %d", (LocalDirectory, RemoteDirectory,
  3061. int(Mode), int(Params))));
  3062. if (FLAGCLEAR(Params, spDelayProgress))
  3063. {
  3064. DoSynchronizeProgress(Data, true);
  3065. }
  3066. try
  3067. {
  3068. bool Found;
  3069. TSearchRec SearchRec;
  3070. Data.LocalFileList = new TStringList();
  3071. Data.LocalFileList->Sorted = true;
  3072. Data.LocalFileList->CaseSensitive = false;
  3073. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (LocalDirectory)),
  3074. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  3075. Found = (FindFirst(Data.LocalDirectory + "*.*", FindAttrs, SearchRec) == 0);
  3076. );
  3077. if (Found)
  3078. {
  3079. try
  3080. {
  3081. AnsiString FileName;
  3082. while (Found)
  3083. {
  3084. FileName = SearchRec.Name;
  3085. // add dirs for recursive mode or when we are interested in newly
  3086. // added subdirs
  3087. int FoundIndex;
  3088. __int64 Size =
  3089. (static_cast<__int64>(SearchRec.FindData.nFileSizeHigh) << 32) +
  3090. SearchRec.FindData.nFileSizeLow;
  3091. TFileMasks::TParams MaskParams;
  3092. MaskParams.Size = Size;
  3093. if ((FileName != ".") && (FileName != "..") &&
  3094. CopyParam->AllowTransfer(Data.LocalDirectory + FileName, osLocal,
  3095. FLAGSET(SearchRec.Attr, faDirectory), MaskParams) &&
  3096. !FFileSystem->TemporaryTransferFile(FileName) &&
  3097. (FLAGCLEAR(Flags, sfFirstLevel) ||
  3098. (Options == NULL) || (Options->Filter == NULL) ||
  3099. Options->Filter->Find(FileName, FoundIndex)))
  3100. {
  3101. TSynchronizeFileData * FileData = new TSynchronizeFileData;
  3102. FILETIME LocalLastWriteTime;
  3103. SYSTEMTIME SystemLastWriteTime;
  3104. FileTimeToLocalFileTime(&SearchRec.FindData.ftLastWriteTime, &LocalLastWriteTime);
  3105. FileTimeToSystemTime(&LocalLastWriteTime, &SystemLastWriteTime);
  3106. FileData->IsDirectory = FLAGSET(SearchRec.Attr, faDirectory);
  3107. FileData->Info.Directory = Data.LocalDirectory;
  3108. FileData->Info.Modification = SystemTimeToDateTime(SystemLastWriteTime);
  3109. FileData->Info.ModificationFmt = mfFull;
  3110. FileData->Info.Size = Size;
  3111. FileData->LocalLastWriteTime = SearchRec.FindData.ftLastWriteTime;
  3112. FileData->New = true;
  3113. FileData->Modified = false;
  3114. Data.LocalFileList->AddObject(FileName,
  3115. reinterpret_cast<TObject*>(FileData));
  3116. }
  3117. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (LocalDirectory)),
  3118. Found = (FindNext(SearchRec) == 0);
  3119. );
  3120. }
  3121. }
  3122. __finally
  3123. {
  3124. FindClose(SearchRec);
  3125. }
  3126. // can we expect that ProcessDirectory would take so little time
  3127. // that we can pospone showing progress window until anything actually happens?
  3128. bool Cached = FLAGSET(Params, spUseCache) && SessionData->CacheDirectories &&
  3129. FDirectoryCache->HasFileList(RemoteDirectory);
  3130. if (!Cached && FLAGSET(Params, spDelayProgress))
  3131. {
  3132. DoSynchronizeProgress(Data, true);
  3133. }
  3134. ProcessDirectory(RemoteDirectory, SynchronizeCollectFile, &Data,
  3135. FLAGSET(Params, spUseCache));
  3136. TSynchronizeFileData * FileData;
  3137. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  3138. {
  3139. FileData = reinterpret_cast<TSynchronizeFileData *>
  3140. (Data.LocalFileList->Objects[Index]);
  3141. // add local file either if we are going to upload it
  3142. // (i.e. if it is updated or we want to upload even new files)
  3143. // or if we are going to delete it (i.e. all "new"=obsolete files)
  3144. bool Modified = (FileData->Modified && ((Mode == smBoth) || (Mode == smRemote)));
  3145. bool New = (FileData->New &&
  3146. ((Mode == smLocal) ||
  3147. (((Mode == smBoth) || (Mode == smRemote)) && FLAGCLEAR(Params, spTimestamp))));
  3148. if (Modified || New)
  3149. {
  3150. TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
  3151. try
  3152. {
  3153. ChecklistItem->FileName = Data.LocalFileList->Strings[Index];
  3154. ChecklistItem->IsDirectory = FileData->IsDirectory;
  3155. ChecklistItem->Local = FileData->Info;
  3156. ChecklistItem->FLocalLastWriteTime = FileData->LocalLastWriteTime;
  3157. if (Modified)
  3158. {
  3159. assert(!FileData->MatchingRemoteFile.Directory.IsEmpty());
  3160. ChecklistItem->Remote = FileData->MatchingRemoteFile;
  3161. ChecklistItem->ImageIndex = FileData->MatchingRemoteFileImageIndex;
  3162. }
  3163. else
  3164. {
  3165. ChecklistItem->Remote.Directory = Data.RemoteDirectory;
  3166. }
  3167. if ((Mode == smBoth) || (Mode == smRemote))
  3168. {
  3169. ChecklistItem->Action =
  3170. (Modified ? TSynchronizeChecklist::saUploadUpdate : TSynchronizeChecklist::saUploadNew);
  3171. ChecklistItem->Checked =
  3172. (Modified || FLAGCLEAR(Params, spExistingOnly)) &&
  3173. (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
  3174. FLAGSET(Params, spSubDirs));
  3175. }
  3176. else if ((Mode == smLocal) && FLAGCLEAR(Params, spTimestamp))
  3177. {
  3178. ChecklistItem->Action = TSynchronizeChecklist::saDeleteLocal;
  3179. ChecklistItem->Checked =
  3180. FLAGSET(Params, spDelete) &&
  3181. (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
  3182. FLAGSET(Params, spSubDirs));
  3183. }
  3184. if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
  3185. {
  3186. Data.Checklist->Add(ChecklistItem);
  3187. ChecklistItem = NULL;
  3188. }
  3189. }
  3190. __finally
  3191. {
  3192. delete ChecklistItem;
  3193. }
  3194. }
  3195. }
  3196. }
  3197. }
  3198. __finally
  3199. {
  3200. if (Data.LocalFileList != NULL)
  3201. {
  3202. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  3203. {
  3204. TSynchronizeFileData * FileData = reinterpret_cast<TSynchronizeFileData*>
  3205. (Data.LocalFileList->Objects[Index]);
  3206. delete FileData;
  3207. }
  3208. delete Data.LocalFileList;
  3209. }
  3210. }
  3211. }
  3212. //---------------------------------------------------------------------------
  3213. void __fastcall TTerminal::SynchronizeCollectFile(const AnsiString FileName,
  3214. const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
  3215. {
  3216. TSynchronizeData * Data = static_cast<TSynchronizeData *>(Param);
  3217. int FoundIndex;
  3218. TFileMasks::TParams MaskParams;
  3219. MaskParams.Size = File->Size;
  3220. if (Data->CopyParam->AllowTransfer(
  3221. UnixExcludeTrailingBackslash(File->FullFileName), osRemote,
  3222. File->IsDirectory, MaskParams) &&
  3223. !FFileSystem->TemporaryTransferFile(File->FileName) &&
  3224. (FLAGCLEAR(Data->Flags, sfFirstLevel) ||
  3225. (Data->Options == NULL) || (Data->Options->Filter == NULL) ||
  3226. Data->Options->Filter->Find(File->FileName, FoundIndex)))
  3227. {
  3228. TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
  3229. try
  3230. {
  3231. ChecklistItem->FileName = File->FileName;
  3232. ChecklistItem->IsDirectory = File->IsDirectory;
  3233. ChecklistItem->ImageIndex = File->IconIndex;
  3234. ChecklistItem->Remote.Directory = Data->RemoteDirectory;
  3235. ChecklistItem->Remote.Modification = File->Modification;
  3236. ChecklistItem->Remote.ModificationFmt = File->ModificationFmt;
  3237. ChecklistItem->Remote.Size = File->Size;
  3238. bool Modified = false;
  3239. int LocalIndex = Data->LocalFileList->IndexOf(ChecklistItem->FileName);
  3240. bool New = (LocalIndex < 0);
  3241. if (!New)
  3242. {
  3243. TSynchronizeFileData * LocalData =
  3244. reinterpret_cast<TSynchronizeFileData *>(Data->LocalFileList->Objects[LocalIndex]);
  3245. LocalData->New = false;
  3246. if (File->IsDirectory != LocalData->IsDirectory)
  3247. {
  3248. LogEvent(FORMAT("%s is directory on one side, but file on the another",
  3249. (File->FileName)));
  3250. }
  3251. else if (!File->IsDirectory)
  3252. {
  3253. ChecklistItem->Local = LocalData->Info;
  3254. ReduceDateTimePrecision(ChecklistItem->Local.Modification, File->ModificationFmt);
  3255. bool LocalModified = false;
  3256. // for spTimestamp+spBySize require that the file sizes are the same
  3257. // before comparing file time
  3258. bool TimeCompare =
  3259. FLAGCLEAR(Data->Params, spNotByTime) &&
  3260. (FLAGCLEAR(Data->Params, spTimestamp) ||
  3261. FLAGCLEAR(Data->Params, spBySize) ||
  3262. (ChecklistItem->Local.Size == ChecklistItem->Remote.Size));
  3263. if (TimeCompare &&
  3264. (CompareFileTime(ChecklistItem->Local.Modification,
  3265. ChecklistItem->Remote.Modification) < 0))
  3266. {
  3267. if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
  3268. (Data->Mode == smBoth) || (Data->Mode == smLocal))
  3269. {
  3270. Modified = true;
  3271. }
  3272. else
  3273. {
  3274. LocalModified = true;
  3275. }
  3276. }
  3277. else if (TimeCompare &&
  3278. (CompareFileTime(ChecklistItem->Local.Modification,
  3279. ChecklistItem->Remote.Modification) > 0))
  3280. {
  3281. if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
  3282. (Data->Mode == smBoth) || (Data->Mode == smRemote))
  3283. {
  3284. LocalModified = true;
  3285. }
  3286. else
  3287. {
  3288. Modified = true;
  3289. }
  3290. }
  3291. else if (FLAGSET(Data->Params, spBySize) &&
  3292. (ChecklistItem->Local.Size != ChecklistItem->Remote.Size) &&
  3293. FLAGCLEAR(Data->Params, spTimestamp))
  3294. {
  3295. Modified = true;
  3296. LocalModified = true;
  3297. }
  3298. if (LocalModified)
  3299. {
  3300. LocalData->Modified = true;
  3301. LocalData->MatchingRemoteFile = ChecklistItem->Remote;
  3302. LocalData->MatchingRemoteFileImageIndex = ChecklistItem->ImageIndex;
  3303. }
  3304. }
  3305. else if (FLAGCLEAR(Data->Params, spNoRecurse))
  3306. {
  3307. DoSynchronizeCollectDirectory(
  3308. Data->LocalDirectory + File->FileName,
  3309. Data->RemoteDirectory + File->FileName,
  3310. Data->Mode, Data->CopyParam, Data->Params, Data->OnSynchronizeDirectory,
  3311. Data->Options, (Data->Flags & ~sfFirstLevel),
  3312. Data->Checklist);
  3313. }
  3314. }
  3315. else
  3316. {
  3317. ChecklistItem->Local.Directory = Data->LocalDirectory;
  3318. }
  3319. if (New || Modified)
  3320. {
  3321. assert(!New || !Modified);
  3322. // download the file if it changed or is new and we want to have it locally
  3323. if ((Data->Mode == smBoth) || (Data->Mode == smLocal))
  3324. {
  3325. ChecklistItem->Action =
  3326. (Modified ? TSynchronizeChecklist::saDownloadUpdate : TSynchronizeChecklist::saDownloadNew);
  3327. ChecklistItem->Checked =
  3328. (Modified || FLAGCLEAR(Data->Params, spExistingOnly)) &&
  3329. (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
  3330. FLAGSET(Data->Params, spSubDirs));
  3331. }
  3332. else if ((Data->Mode == smRemote) && New)
  3333. {
  3334. if (FLAGCLEAR(Data->Params, spTimestamp))
  3335. {
  3336. ChecklistItem->Action = TSynchronizeChecklist::saDeleteRemote;
  3337. ChecklistItem->Checked =
  3338. FLAGSET(Data->Params, spDelete) &&
  3339. (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
  3340. FLAGSET(Data->Params, spSubDirs));
  3341. }
  3342. }
  3343. if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
  3344. {
  3345. ChecklistItem->FRemoteFile = File->Duplicate();
  3346. Data->Checklist->Add(ChecklistItem);
  3347. ChecklistItem = NULL;
  3348. }
  3349. }
  3350. }
  3351. __finally
  3352. {
  3353. delete ChecklistItem;
  3354. }
  3355. }
  3356. }
  3357. //---------------------------------------------------------------------------
  3358. void __fastcall TTerminal::SynchronizeApply(TSynchronizeChecklist * Checklist,
  3359. const AnsiString LocalDirectory, const AnsiString RemoteDirectory,
  3360. const TCopyParamType * CopyParam, int Params,
  3361. TSynchronizeDirectory OnSynchronizeDirectory)
  3362. {
  3363. TSynchronizeData Data;
  3364. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  3365. int CopyParams =
  3366. FLAGMASK(FLAGSET(Params, spNoConfirmation), cpNoConfirmation);
  3367. TCopyParamType SyncCopyParam = *CopyParam;
  3368. SyncCopyParam.PreserveTime = true;
  3369. TStringList * DownloadList = new TStringList();
  3370. TStringList * DeleteRemoteList = new TStringList();
  3371. TStringList * UploadList = new TStringList();
  3372. TStringList * DeleteLocalList = new TStringList();
  3373. BeginTransaction();
  3374. try
  3375. {
  3376. int IIndex = 0;
  3377. while (IIndex < Checklist->Count)
  3378. {
  3379. const TSynchronizeChecklist::TItem * ChecklistItem;
  3380. DownloadList->Clear();
  3381. DeleteRemoteList->Clear();
  3382. UploadList->Clear();
  3383. DeleteLocalList->Clear();
  3384. ChecklistItem = Checklist->Item[IIndex];
  3385. AnsiString CurrentLocalDirectory = ChecklistItem->Local.Directory;
  3386. AnsiString CurrentRemoteDirectory = ChecklistItem->Remote.Directory;
  3387. LogEvent(FORMAT("Synchronizing local directory '%s' with remote directory '%s', "
  3388. "params = %d", (CurrentLocalDirectory, CurrentRemoteDirectory, int(Params))));
  3389. int Count = 0;
  3390. while ((IIndex < Checklist->Count) &&
  3391. (Checklist->Item[IIndex]->Local.Directory == CurrentLocalDirectory) &&
  3392. (Checklist->Item[IIndex]->Remote.Directory == CurrentRemoteDirectory))
  3393. {
  3394. ChecklistItem = Checklist->Item[IIndex];
  3395. if (ChecklistItem->Checked)
  3396. {
  3397. Count++;
  3398. if (FLAGSET(Params, spTimestamp))
  3399. {
  3400. switch (ChecklistItem->Action)
  3401. {
  3402. case TSynchronizeChecklist::saDownloadUpdate:
  3403. DownloadList->AddObject(
  3404. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  3405. ChecklistItem->FileName,
  3406. (TObject *)(ChecklistItem));
  3407. break;
  3408. case TSynchronizeChecklist::saUploadUpdate:
  3409. UploadList->AddObject(
  3410. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  3411. ChecklistItem->FileName,
  3412. (TObject *)(ChecklistItem));
  3413. break;
  3414. default:
  3415. assert(false);
  3416. break;
  3417. }
  3418. }
  3419. else
  3420. {
  3421. switch (ChecklistItem->Action)
  3422. {
  3423. case TSynchronizeChecklist::saDownloadNew:
  3424. case TSynchronizeChecklist::saDownloadUpdate:
  3425. DownloadList->AddObject(
  3426. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  3427. ChecklistItem->FileName,
  3428. ChecklistItem->FRemoteFile);
  3429. break;
  3430. case TSynchronizeChecklist::saDeleteRemote:
  3431. DeleteRemoteList->AddObject(
  3432. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  3433. ChecklistItem->FileName,
  3434. ChecklistItem->FRemoteFile);
  3435. break;
  3436. case TSynchronizeChecklist::saUploadNew:
  3437. case TSynchronizeChecklist::saUploadUpdate:
  3438. UploadList->Add(
  3439. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  3440. ChecklistItem->FileName);
  3441. break;
  3442. case TSynchronizeChecklist::saDeleteLocal:
  3443. DeleteLocalList->Add(
  3444. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  3445. ChecklistItem->FileName);
  3446. break;
  3447. default:
  3448. assert(false);
  3449. break;
  3450. }
  3451. }
  3452. }
  3453. IIndex++;
  3454. }
  3455. // prevent showing/updating of progress dialog if there's nothing to do
  3456. if (Count > 0)
  3457. {
  3458. Data.LocalDirectory = IncludeTrailingBackslash(CurrentLocalDirectory);
  3459. Data.RemoteDirectory = UnixIncludeTrailingBackslash(CurrentRemoteDirectory);
  3460. DoSynchronizeProgress(Data, false);
  3461. if (FLAGSET(Params, spTimestamp))
  3462. {
  3463. if (DownloadList->Count > 0)
  3464. {
  3465. ProcessFiles(DownloadList, foSetProperties,
  3466. SynchronizeLocalTimestamp, NULL, osLocal);
  3467. }
  3468. if (UploadList->Count > 0)
  3469. {
  3470. ProcessFiles(UploadList, foSetProperties,
  3471. SynchronizeRemoteTimestamp);
  3472. }
  3473. }
  3474. else
  3475. {
  3476. if ((DownloadList->Count > 0) &&
  3477. !CopyToLocal(DownloadList, Data.LocalDirectory, &SyncCopyParam, CopyParams))
  3478. {
  3479. Abort();
  3480. }
  3481. if ((DeleteRemoteList->Count > 0) &&
  3482. !DeleteFiles(DeleteRemoteList))
  3483. {
  3484. Abort();
  3485. }
  3486. if ((UploadList->Count > 0) &&
  3487. !CopyToRemote(UploadList, Data.RemoteDirectory, &SyncCopyParam, CopyParams))
  3488. {
  3489. Abort();
  3490. }
  3491. if ((DeleteLocalList->Count > 0) &&
  3492. !DeleteLocalFiles(DeleteLocalList))
  3493. {
  3494. Abort();
  3495. }
  3496. }
  3497. }
  3498. }
  3499. }
  3500. __finally
  3501. {
  3502. delete DownloadList;
  3503. delete DeleteRemoteList;
  3504. delete UploadList;
  3505. delete DeleteLocalList;
  3506. EndTransaction();
  3507. }
  3508. }
  3509. //---------------------------------------------------------------------------
  3510. void __fastcall TTerminal::DoSynchronizeProgress(const TSynchronizeData & Data,
  3511. bool Collect)
  3512. {
  3513. if (Data.OnSynchronizeDirectory != NULL)
  3514. {
  3515. bool Continue = true;
  3516. Data.OnSynchronizeDirectory(Data.LocalDirectory, Data.RemoteDirectory,
  3517. Continue, Collect);
  3518. if (!Continue)
  3519. {
  3520. Abort();
  3521. }
  3522. }
  3523. }
  3524. //---------------------------------------------------------------------------
  3525. void __fastcall TTerminal::SynchronizeLocalTimestamp(const AnsiString /*FileName*/,
  3526. const TRemoteFile * File, void * /*Param*/)
  3527. {
  3528. const TSynchronizeChecklist::TItem * ChecklistItem =
  3529. reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
  3530. AnsiString LocalFile =
  3531. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  3532. ChecklistItem->FileName;
  3533. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (LocalFile)),
  3534. HANDLE Handle;
  3535. OpenLocalFile(LocalFile, GENERIC_WRITE, NULL, &Handle,
  3536. NULL, NULL, NULL, NULL);
  3537. FILETIME WrTime = DateTimeToFileTime(ChecklistItem->Remote.Modification,
  3538. SessionData->DSTMode);
  3539. bool Result = SetFileTime(Handle, NULL, NULL, &WrTime);
  3540. CloseHandle(Handle);
  3541. if (!Result)
  3542. {
  3543. Abort();
  3544. }
  3545. );
  3546. }
  3547. //---------------------------------------------------------------------------
  3548. void __fastcall TTerminal::SynchronizeRemoteTimestamp(const AnsiString /*FileName*/,
  3549. const TRemoteFile * File, void * /*Param*/)
  3550. {
  3551. const TSynchronizeChecklist::TItem * ChecklistItem =
  3552. reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
  3553. TRemoteProperties Properties;
  3554. Properties.Valid << vpModification;
  3555. Properties.Modification = ConvertTimestampToUnix(ChecklistItem->FLocalLastWriteTime,
  3556. SessionData->DSTMode);
  3557. // unfortunatelly we never have a remote file here
  3558. assert(ChecklistItem->FRemoteFile == NULL);
  3559. ChangeFileProperties(
  3560. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) + ChecklistItem->FileName,
  3561. NULL, &Properties);
  3562. }
  3563. //---------------------------------------------------------------------------
  3564. void __fastcall TTerminal::SpaceAvailable(const AnsiString Path,
  3565. TSpaceAvailable & ASpaceAvailable)
  3566. {
  3567. assert(IsCapable[fcCheckingSpaceAvailable]);
  3568. try
  3569. {
  3570. FFileSystem->SpaceAvailable(Path, ASpaceAvailable);
  3571. }
  3572. catch (Exception &E)
  3573. {
  3574. CommandError(&E, FMTLOAD(SPACE_AVAILABLE_ERROR, (Path)));
  3575. }
  3576. }
  3577. //---------------------------------------------------------------------------
  3578. const TSessionInfo & __fastcall TTerminal::GetSessionInfo()
  3579. {
  3580. return FFileSystem->GetSessionInfo();
  3581. }
  3582. //---------------------------------------------------------------------------
  3583. const TFileSystemInfo & __fastcall TTerminal::GetFileSystemInfo(bool Retrieve)
  3584. {
  3585. return FFileSystem->GetFileSystemInfo(Retrieve);
  3586. }
  3587. //---------------------------------------------------------------------
  3588. AnsiString __fastcall TTerminal::GetPassword()
  3589. {
  3590. AnsiString Result;
  3591. // FPassword is empty also when stored password was used
  3592. if (FPassword.IsEmpty())
  3593. {
  3594. Result = SessionData->Password;
  3595. }
  3596. else
  3597. {
  3598. Result = DecryptPassword(FPassword, SessionData->SessionName);
  3599. }
  3600. return Result;
  3601. }
  3602. //---------------------------------------------------------------------
  3603. bool __fastcall TTerminal::GetStoredCredentialsTried()
  3604. {
  3605. bool Result;
  3606. if (FFileSystem != NULL)
  3607. {
  3608. Result = FFileSystem->GetStoredCredentialsTried();
  3609. }
  3610. else
  3611. {
  3612. assert(FSecureShell != NULL);
  3613. Result = FSecureShell->GetStoredCredentialsTried();
  3614. }
  3615. return Result;
  3616. }
  3617. //---------------------------------------------------------------------------
  3618. bool __fastcall TTerminal::CopyToRemote(TStrings * FilesToCopy,
  3619. const AnsiString TargetDir, const TCopyParamType * CopyParam, int Params)
  3620. {
  3621. assert(FFileSystem);
  3622. assert(FilesToCopy);
  3623. assert(IsCapable[fcNewerOnlyUpload] || FLAGCLEAR(Params, cpNewerOnly));
  3624. bool Result = false;
  3625. bool DisconnectWhenComplete = false;
  3626. try
  3627. {
  3628. __int64 Size;
  3629. if (CopyParam->CalculateSize)
  3630. {
  3631. // dirty trick: when moving, do not pass copy param to avoid exclude mask
  3632. CalculateLocalFilesSize(FilesToCopy, Size,
  3633. (FLAGCLEAR(Params, cpDelete) ? CopyParam : NULL));
  3634. }
  3635. TFileOperationProgressType OperationProgress(FOnProgress, FOnFinished);
  3636. OperationProgress.Start((Params & cpDelete ? foMove : foCopy), osLocal,
  3637. FilesToCopy->Count, Params & cpTemporary, TargetDir);
  3638. OperationProgress.YesToNewer = FLAGSET(Params, cpNewerOnly);
  3639. FOperationProgress = &OperationProgress;
  3640. try
  3641. {
  3642. if (CopyParam->CalculateSize)
  3643. {
  3644. OperationProgress.SetTotalSize(Size);
  3645. }
  3646. AnsiString UnlockedTargetDir = TranslateLockedPath(TargetDir, false);
  3647. BeginTransaction();
  3648. try
  3649. {
  3650. if (Log->Logging)
  3651. {
  3652. LogEvent(FORMAT("Copying %d files/directories to remote directory "
  3653. "\"%s\"", (FilesToCopy->Count, TargetDir)));
  3654. LogEvent(CopyParam->LogStr);
  3655. }
  3656. FFileSystem->CopyToRemote(FilesToCopy, UnlockedTargetDir,
  3657. CopyParam, Params, &OperationProgress, DisconnectWhenComplete);
  3658. }
  3659. __finally
  3660. {
  3661. if (Active)
  3662. {
  3663. ReactOnCommand(fsCopyToRemote);
  3664. }
  3665. EndTransaction();
  3666. }
  3667. if (OperationProgress.Cancel == csContinue)
  3668. {
  3669. Result = true;
  3670. }
  3671. }
  3672. __finally
  3673. {
  3674. OperationProgress.Stop();
  3675. FOperationProgress = NULL;
  3676. }
  3677. }
  3678. catch (Exception &E)
  3679. {
  3680. CommandError(&E, LoadStr(TOREMOTE_COPY_ERROR));
  3681. DisconnectWhenComplete = false;
  3682. }
  3683. if (DisconnectWhenComplete) CloseOnCompletion();
  3684. return Result;
  3685. }
  3686. //---------------------------------------------------------------------------
  3687. bool __fastcall TTerminal::CopyToLocal(TStrings * FilesToCopy,
  3688. const AnsiString TargetDir, const TCopyParamType * CopyParam, int Params)
  3689. {
  3690. assert(FFileSystem);
  3691. // see scp.c: sink(), tolocal()
  3692. bool Result = false;
  3693. bool OwnsFileList = (FilesToCopy == NULL);
  3694. bool DisconnectWhenComplete = false;
  3695. try
  3696. {
  3697. if (OwnsFileList)
  3698. {
  3699. FilesToCopy = new TStringList();
  3700. FilesToCopy->Assign(Files->SelectedFiles);
  3701. }
  3702. BeginTransaction();
  3703. try
  3704. {
  3705. __int64 TotalSize;
  3706. bool TotalSizeKnown = false;
  3707. TFileOperationProgressType OperationProgress(FOnProgress, FOnFinished);
  3708. if (CopyParam->CalculateSize)
  3709. {
  3710. ExceptionOnFail = true;
  3711. try
  3712. {
  3713. // dirty trick: when moving, do not pass copy param to avoid exclude mask
  3714. CalculateFilesSize(FilesToCopy, TotalSize, csIgnoreErrors,
  3715. (FLAGCLEAR(Params, cpDelete) ? CopyParam : NULL));
  3716. TotalSizeKnown = true;
  3717. }
  3718. __finally
  3719. {
  3720. ExceptionOnFail = false;
  3721. }
  3722. }
  3723. OperationProgress.Start((Params & cpDelete ? foMove : foCopy), osRemote,
  3724. FilesToCopy->Count, Params & cpTemporary, TargetDir);
  3725. OperationProgress.YesToNewer = FLAGSET(Params, cpNewerOnly);
  3726. FOperationProgress = &OperationProgress;
  3727. try
  3728. {
  3729. if (TotalSizeKnown)
  3730. {
  3731. OperationProgress.SetTotalSize(TotalSize);
  3732. }
  3733. try
  3734. {
  3735. try
  3736. {
  3737. FFileSystem->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params,
  3738. &OperationProgress, DisconnectWhenComplete);
  3739. }
  3740. __finally
  3741. {
  3742. if (Active)
  3743. {
  3744. ReactOnCommand(fsCopyToLocal);
  3745. }
  3746. }
  3747. }
  3748. catch (Exception &E)
  3749. {
  3750. CommandError(&E, LoadStr(TOLOCAL_COPY_ERROR));
  3751. DisconnectWhenComplete = false;
  3752. }
  3753. if (OperationProgress.Cancel == csContinue)
  3754. {
  3755. Result = true;
  3756. }
  3757. }
  3758. __finally
  3759. {
  3760. FOperationProgress = NULL;
  3761. OperationProgress.Stop();
  3762. }
  3763. }
  3764. __finally
  3765. {
  3766. // If session is still active (no fatal error) we reload directory
  3767. // by calling EndTransaction
  3768. EndTransaction();
  3769. }
  3770. }
  3771. __finally
  3772. {
  3773. if (OwnsFileList) delete FilesToCopy;
  3774. }
  3775. if (DisconnectWhenComplete) CloseOnCompletion();
  3776. return Result;
  3777. }
  3778. //---------------------------------------------------------------------------
  3779. __fastcall TSecondaryTerminal::TSecondaryTerminal(TTerminal * MainTerminal,
  3780. TSessionData * ASessionData, TConfiguration * Configuration, const AnsiString & Name) :
  3781. TTerminal(ASessionData, Configuration),
  3782. FMainTerminal(MainTerminal), FMasterPasswordTried(false)
  3783. {
  3784. Log->Parent = FMainTerminal->Log;
  3785. Log->Name = Name;
  3786. SessionData->NonPersistant();
  3787. assert(FMainTerminal != NULL);
  3788. if (!FMainTerminal->UserName.IsEmpty())
  3789. {
  3790. SessionData->UserName = FMainTerminal->UserName;
  3791. }
  3792. }
  3793. //---------------------------------------------------------------------------
  3794. void __fastcall TSecondaryTerminal::DirectoryLoaded(TRemoteFileList * FileList)
  3795. {
  3796. FMainTerminal->DirectoryLoaded(FileList);
  3797. assert(FileList != NULL);
  3798. }
  3799. //---------------------------------------------------------------------------
  3800. void __fastcall TSecondaryTerminal::DirectoryModified(const AnsiString Path,
  3801. bool SubDirs)
  3802. {
  3803. // clear cache of main terminal
  3804. FMainTerminal->DirectoryModified(Path, SubDirs);
  3805. }
  3806. //---------------------------------------------------------------------------
  3807. bool __fastcall TSecondaryTerminal::DoPromptUser(TSessionData * Data,
  3808. AnsiString Prompt, TPromptKind Kind, AnsiString & Response)
  3809. {
  3810. bool Result = false;
  3811. if (!FMasterPasswordTried &&
  3812. ((Kind == pkPassword) || (Kind == pkPassphrase) || (Kind == pkServerPrompt)))
  3813. {
  3814. // let's expect that the main session is already authenticated and its password
  3815. // is not written after, so no locking is necessary
  3816. // (no longer true, once the main session can be reconnected)
  3817. Response = FMainTerminal->Password;
  3818. if (!Response.IsEmpty())
  3819. {
  3820. Result = true;
  3821. }
  3822. FMasterPasswordTried = true;
  3823. }
  3824. if (!Result)
  3825. {
  3826. Result = TTerminal::DoPromptUser(Data, Prompt, Kind, Response);
  3827. }
  3828. return Result;
  3829. }
  3830. //---------------------------------------------------------------------------
  3831. __fastcall TTerminalList::TTerminalList(TConfiguration * AConfiguration) :
  3832. TObjectList()
  3833. {
  3834. assert(AConfiguration);
  3835. FConfiguration = AConfiguration;
  3836. }
  3837. //---------------------------------------------------------------------------
  3838. __fastcall TTerminalList::~TTerminalList()
  3839. {
  3840. assert(Count == 0);
  3841. }
  3842. //---------------------------------------------------------------------------
  3843. TTerminal * __fastcall TTerminalList::CreateTerminal(TSessionData * Data)
  3844. {
  3845. return new TTerminal(Data, FConfiguration);
  3846. }
  3847. //---------------------------------------------------------------------------
  3848. TTerminal * __fastcall TTerminalList::NewTerminal(TSessionData * Data)
  3849. {
  3850. TTerminal * Terminal = CreateTerminal(Data);
  3851. Add(Terminal);
  3852. return Terminal;
  3853. }
  3854. //---------------------------------------------------------------------------
  3855. void __fastcall TTerminalList::FreeTerminal(TTerminal * Terminal)
  3856. {
  3857. assert(IndexOf(Terminal) >= 0);
  3858. Remove(Terminal);
  3859. }
  3860. //---------------------------------------------------------------------------
  3861. void __fastcall TTerminalList::FreeAndNullTerminal(TTerminal * & Terminal)
  3862. {
  3863. TTerminal * T = Terminal;
  3864. Terminal = NULL;
  3865. FreeTerminal(T);
  3866. }
  3867. //---------------------------------------------------------------------------
  3868. TTerminal * __fastcall TTerminalList::GetTerminal(int Index)
  3869. {
  3870. return dynamic_cast<TTerminal *>(Items[Index]);
  3871. }
  3872. //---------------------------------------------------------------------------
  3873. int __fastcall TTerminalList::GetActiveCount()
  3874. {
  3875. int Result = 0;
  3876. TTerminal * Terminal;
  3877. for (int i = 0; i < Count; i++)
  3878. {
  3879. Terminal = Terminals[i];
  3880. if (Terminal->Active)
  3881. {
  3882. Result++;
  3883. }
  3884. }
  3885. return Result;
  3886. }
  3887. //---------------------------------------------------------------------------
  3888. void __fastcall TTerminalList::Idle()
  3889. {
  3890. TTerminal * Terminal;
  3891. for (int i = 0; i < Count; i++)
  3892. {
  3893. Terminal = Terminals[i];
  3894. if (Terminal->Status == ssOpened)
  3895. {
  3896. Terminal->Idle();
  3897. }
  3898. }
  3899. }