Terminal.cpp 124 KB

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