Terminal.cpp 148 KB

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